Compare commits

..

21 Commits

Author SHA1 Message Date
e3f93fed10 Update "/api/locust/v01/AcceptJSON_KAZ" 2025-07-20 19:45:59 +05:00
884d3ceb62 import kaz 2025-07-17 07:12:10 +05:00
686109361f Import mod 2025-07-15 07:40:21 +05:00
914b2aae03 add throw 2025-07-14 17:34:41 +05:00
d254140b91 Download reports repair 2025-07-14 15:07:32 +05:00
d2c1f9c7da UZB Update 2025-07-14 11:58:43 +05:00
3c44dac29e UZB integration 2025-07-14 07:37:34 +05:00
39db27fca1 repair warn_air 2025-07-04 07:27:49 +05:00
6e4c74c426 Repair warning 2025-07-03 17:55:01 +05:00
91a1e86415 IVI modif 2025-07-03 07:35:02 +05:00
36783d2de7 Testing /api/locust/v01/SendWarning 2025-06-30 07:27:44 +05:00
7d8ab90e49 Merge branch 'develop' of https://git.mesh.kz/igor/org.ccalm.main into develop
# Conflicts:
#	src/main/java/org/ccalm/main/AcceptJSON.java
#	src/main/java/org/ccalm/main/SendWarning.java
#	src/main/java/org/ccalm/main/engine/EngineController.java
#	src/main/java/org/ccalm/main/login/LoginController.java
#	src/main/java/org/ccalm/main/utils/LTools.java
2025-06-24 23:22:38 +05:00
ed14a3fa9e Preparing for the transition to REST API 2025-06-24 23:08:38 +05:00
9f45e71b59 Exception message + exception object save to log 2025-05-20 13:03:53 +05:00
3e0ba9279b Local tools 2025-03-28 15:33:36 +05:00
1722d20e8e Merge branch 'develop' of https://git.dirt.kz/igor/org.ccalm.main into develop 2025-03-28 13:22:57 +05:00
76ebe97f24 dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 2025-03-28 13:22:42 +05:00
0de815893f import from usbekistan 2025-03-28 07:45:54 +05:00
afd6abd9e3 + 2025-03-19 07:26:54 +05:00
721b4cac26 + 2025-03-18 07:33:39 +05:00
43185b31ea Импорт анкет из узбекистана 2025-03-17 07:28:52 +05:00
41 changed files with 5005 additions and 3741 deletions

View File

@ -1,5 +1,5 @@
server: server:
port: 8081 port: 8083
ssl: ssl:
enabled: true enabled: true
key-store: classpath:keystore.jks key-store: classpath:keystore.jks
@ -8,13 +8,16 @@ server:
spring: spring:
application: application:
name: org.ccalm.main name: org-ccalm-main
datasource: datasource:
url: jdbc:postgresql://91.201.214.156:5432/CCALM?ApplicationName=org_ccalm_main&ssl=true&sslmode=require&connectTimeout=10000&socketTimeout=10000 #url: jdbc:postgresql://almaty.ccalm.org:5432/CCALM?ApplicationName=org_ccalm_main&ssl=true&sslmode=require&connectTimeout=10000&socketTimeout=10000
#url: jdbc:postgresql://ccalm.org:5432/CCALM?ApplicationName=org_ccalm_main&ssl=true&sslmode=require&connectTimeout=10000&socketTimeout=10000
url: jdbc:postgresql://127.0.0.1:5432/CCALM?ApplicationName=org_ccalm_main&ssl=true&sslmode=require&connectTimeout=10000&socketTimeout=10000
username: postgres username: postgres
password: 309A86FF65A78FB428F4E38DFE35F730 password: 309A86FF65A78FB428F4E38DFE35F730
driver-class-name: org.postgresql.Driver driver-class-name: org.postgresql.Driver
hikari: hikari:
connection-init-sql: "SET timezone TO 'UTC';"
maximum-pool-size: 10 maximum-pool-size: 10
minimum-idle: 5 minimum-idle: 5
max-lifetime: 1740000 max-lifetime: 1740000

37
pom.xml
View File

@ -10,7 +10,7 @@
</parent> </parent>
<groupId>org.ccalm</groupId> <groupId>org.ccalm</groupId>
<artifactId>main</artifactId> <artifactId>main</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>1.0.3</version>
<name>main</name> <name>main</name>
<description>main</description> <description>main</description>
<properties> <properties>
@ -44,12 +44,12 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <!--dependency>
<groupId>jakarta.servlet</groupId> <groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId> <artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version> <version>6.0.0</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency-->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId> <artifactId>spring-boot-starter-data-jdbc</artifactId>
@ -57,7 +57,7 @@
<dependency> <dependency>
<groupId>org.postgresql</groupId> <groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId> <artifactId>postgresql</artifactId>
<version>42.7.5</version> <version>42.7.7</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.json</groupId> <groupId>org.json</groupId>
@ -69,16 +69,22 @@
<artifactId>mail</artifactId> <artifactId>mail</artifactId>
<version>1.4</version> <version>1.4</version>
</dependency> </dependency>
<dependency> <!--dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>1.3.2</version> <version>1.3.2</version>
</dependency-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.15.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.logstash.logback</groupId> <groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId> <artifactId>logstash-logback-encoder</artifactId>
<version>6.6</version> <version>7.4</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/edu.ucar/netcdfAll --> <!-- https://mvnrepository.com/artifact/edu.ucar/netcdfAll -->
<dependency> <dependency>
@ -121,10 +127,27 @@
<artifactId>spring-jdbc</artifactId> <artifactId>spring-jdbc</artifactId>
<version>6.1.12</version> <version>6.1.12</version>
</dependency> </dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.8.4</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>org-ccalm-main</finalName>
<plugins> <plugins>
<plugin> <plugin>
@ -141,7 +164,7 @@
<version>2.22.2</version> <version>2.22.2</version>
<configuration> <configuration>
<systemPropertyVariables> <systemPropertyVariables>
<spring.config.location>file:application.properties</spring.config.location> <spring.config.location>file:org-ccalm-main.yml</spring.config.location>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -0,0 +1,12 @@
package logging;
public interface Logger {
void debug(String msg);
void info(String msg);
void warn(String msg);
void error(String msg);
static Logger getLogger(Class<?> clazz) {
return LoggerFactory.createLogger(clazz); // Подменяется реализацией
}
}

View File

@ -0,0 +1,22 @@
package logging;
public class LoggerFactory {
public static Logger createLogger(Class<?> clazz) {
// Тут выбираешь реализацию по флагу/условию
//if (isAndroid()) {
// return new AndroidLogger(clazz);
//} else {
return new SLF4JLogger(clazz);
//}
}
private static boolean isAndroid() {
try {
Class.forName("android.os.Build");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}

View File

@ -0,0 +1,18 @@
package logging;
import org.ccalm.main.MainController;
import org.slf4j.LoggerFactory;
public class SLF4JLogger implements Logger {
private final org.slf4j.Logger logger;
public SLF4JLogger(Class<?> clazz) {
this.logger = LoggerFactory.getLogger(clazz);
}
public void debug(String msg) { logger.debug(msg); }
public void info(String msg) { logger.info(msg); }
public void warn(String msg) { logger.warn(msg); }
public void error(String msg) { logger.error(msg); }
}

View File

@ -25,6 +25,7 @@ import java.util.*;
//import javax.servlet.ServletContext; //import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.Part; //import javax.servlet.http.Part;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
@ -90,7 +91,7 @@ public class AcceptASDCController implements ServletContextAware {
return hexString.toString(); return hexString.toString();
} catch (NoSuchAlgorithmException ex) { } catch (NoSuchAlgorithmException ex) {
logger.error("Error",ex); logger.error(ex.getMessage(),ex);
} }
return ""; return "";
} }
@ -134,7 +135,7 @@ public class AcceptASDCController implements ServletContextAware {
} }
//Update lon lat //Update lon lat
@RequestMapping(value = "/update",method = { RequestMethod.GET }) @RequestMapping(value = {"/update", "/api/locust/v01/update"},method = { RequestMethod.GET })
@ResponseBody @ResponseBody
public Object update_lon_lat() { public Object update_lon_lat() {
JSONObject result = new JSONObject(); JSONObject result = new JSONObject();
@ -155,7 +156,7 @@ public class AcceptASDCController implements ServletContextAware {
// Чтение файла // Чтение файла
BufferedReader reader = new BufferedReader(new FileReader("O:\\temp\\Новая папка\\errors.log")); BufferedReader reader = new BufferedReader(new FileReader("O:\\temp\\Новая папка\\errors.log"));
StringBuilder content = new StringBuilder(); StringBuilder content = new StringBuilder(1024);
String line; String line;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
content.append(line); content.append(line);
@ -206,7 +207,7 @@ public class AcceptASDCController implements ServletContextAware {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return obj.toString(); return obj.toString();
} }
stmt.close(); stmt.close();
@ -221,7 +222,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -233,7 +234,7 @@ public class AcceptASDCController implements ServletContextAware {
} }
//Save or update your health questionnaire //Save or update your health questionnaire
@RequestMapping(value = "/asdc/frmlocusthealth/",method = { RequestMethod.GET, RequestMethod.POST },produces = "application/json") @RequestMapping(value = {"/asdc/frmlocusthealth/", "/api/locust/v01/asdc/frmlocusthealth/"},method = { RequestMethod.GET, RequestMethod.POST },produces = "application/json")
@ResponseBody @ResponseBody
public Object uploadFrmLocustHealth(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestBody(required=false) byte[] reqData) { public Object uploadFrmLocustHealth(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestBody(required=false) byte[] reqData) {
JSONObject result = new JSONObject(); JSONObject result = new JSONObject();
@ -274,7 +275,7 @@ public class AcceptASDCController implements ServletContextAware {
rs = st.executeQuery("select 1 from main.frmlocusthealth where uid='"+uid+"'"); rs = st.executeQuery("select 1 from main.frmlocusthealth where uid='"+uid+"'");
} catch( SQLException ex ) { } catch( SQLException ex ) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
@ -288,7 +289,7 @@ public class AcceptASDCController implements ServletContextAware {
st.close(); st.close();
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
@ -590,7 +591,7 @@ public class AcceptASDCController implements ServletContextAware {
stmtn = new PreparedStatementNamed(conn, sql); stmtn = new PreparedStatementNamed(conn, sql);
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()+" "+sql); logRotate(data_dir+"errors.log",ex.getMessage()+" "+sql);
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
@ -806,7 +807,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt.execute(); stmt.execute();
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
@ -818,7 +819,7 @@ public class AcceptASDCController implements ServletContextAware {
String tmpDir = "temp"+File.separator; String tmpDir = "temp"+File.separator;
try{ new File(dataDir+tmpDir).mkdirs(); }catch (Exception ex) { try{ new File(dataDir+tmpDir).mkdirs(); }catch (Exception ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
@ -880,7 +881,7 @@ public class AcceptASDCController implements ServletContextAware {
ex.printStackTrace(); ex.printStackTrace();
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return result.toString(); return result.toString();
}finally { }finally {
try{ if(conn!=null) conn.close(); }catch(Exception e){} try{ if(conn!=null) conn.close(); }catch(Exception e){}
@ -889,7 +890,7 @@ public class AcceptASDCController implements ServletContextAware {
} }
// To authorize a tablet using a QR code from "ScanActivity" form // To authorize a tablet using a QR code from "ScanActivity" form
@RequestMapping(value = "/asdc/qrcode/",method = { RequestMethod.GET, RequestMethod.POST },produces = "application/json") @RequestMapping(value = {"/asdc/qrcode/", "/api/locust/v01/asdc/qrcode/"},method = { RequestMethod.GET, RequestMethod.POST },produces = "application/json")
@ResponseBody @ResponseBody
public Object uploadJSON(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestBody(required=false) byte[] reqData) { public Object uploadJSON(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestBody(required=false) byte[] reqData) {
@ -942,7 +943,7 @@ public class AcceptASDCController implements ServletContextAware {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return obj.toString(); return obj.toString();
} }
try { try {
@ -951,7 +952,7 @@ public class AcceptASDCController implements ServletContextAware {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return obj.toString(); return obj.toString();
} }
try { try {
@ -960,7 +961,7 @@ public class AcceptASDCController implements ServletContextAware {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return obj.toString(); return obj.toString();
} }
@ -972,7 +973,7 @@ public class AcceptASDCController implements ServletContextAware {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return obj.toString(); return obj.toString();
} }
@ -983,7 +984,7 @@ public class AcceptASDCController implements ServletContextAware {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return obj.toString(); return obj.toString();
} }
@ -993,7 +994,7 @@ public class AcceptASDCController implements ServletContextAware {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return obj.toString(); return obj.toString();
} }
@ -1008,7 +1009,7 @@ public class AcceptASDCController implements ServletContextAware {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return obj.toString(); return obj.toString();
} }
if(rs!=null) if(rs!=null)
@ -1028,7 +1029,7 @@ public class AcceptASDCController implements ServletContextAware {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("error_code",1); obj.put("error_code",1);
obj.put("error_message", ex.getMessage()); obj.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return obj.toString(); return obj.toString();
} }
}else { }else {
@ -1042,7 +1043,7 @@ public class AcceptASDCController implements ServletContextAware {
ex.printStackTrace(); ex.printStackTrace();
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
return result.toString(); return result.toString();
}finally { }finally {
try{ if(conn!=null) conn.close(); }catch(Exception e){} try{ if(conn!=null) conn.close(); }catch(Exception e){}
@ -1050,7 +1051,7 @@ public class AcceptASDCController implements ServletContextAware {
return result.toString(); return result.toString();
} }
@RequestMapping(value = "/get/",method = { RequestMethod.GET, RequestMethod.POST },produces = "application/xml; charset=utf-8") @RequestMapping(value = {"/get/", "/api/locust/v01/get/"},method = { RequestMethod.GET, RequestMethod.POST },produces = "application/xml; charset=utf-8")
@ResponseBody @ResponseBody
public Object uploadXML(HttpServletResponse response, @RequestHeader(required=false,name="Content-Type") String contentType, @RequestBody(required=false) byte[] reqData) { public Object uploadXML(HttpServletResponse response, @RequestHeader(required=false,name="Content-Type") String contentType, @RequestBody(required=false) byte[] reqData) {
@ -1067,7 +1068,7 @@ public class AcceptASDCController implements ServletContextAware {
String tmpDir = "temp"+File.separator; String tmpDir = "temp"+File.separator;
try{ new File(dataDir+tmpDir).mkdirs(); }catch (Exception ex) { try{ new File(dataDir+tmpDir).mkdirs(); }catch (Exception ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"; result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>";
return result; return result;
} }
@ -1102,14 +1103,14 @@ public class AcceptASDCController implements ServletContextAware {
stm.execute("SET timezone TO 'UTC';"); stm.execute("SET timezone TO 'UTC';");
} catch( SQLException ex ) { } catch( SQLException ex ) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"; result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>";
return result; return result;
} }
stm.close(); stm.close();
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"; result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>";
return result; return result;
} }
@ -1130,11 +1131,12 @@ public class AcceptASDCController implements ServletContextAware {
try { try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(body); doc = dBuilder.parse(body);
} catch (Exception ex) { } catch (Exception ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<metadata fn=\"-1\"><![CDATA[Parsing request error!]]></metadata>"; result="<metadata fn=\"-1\"><![CDATA[Parsing request error!]]></metadata>";
return result; return result;
} }
@ -1159,7 +1161,7 @@ public class AcceptASDCController implements ServletContextAware {
rs = st.executeQuery("select 1 from main.frmlocust where uid='"+uid+"'"); rs = st.executeQuery("select 1 from main.frmlocust where uid='"+uid+"'");
} catch( SQLException ex ) { } catch( SQLException ex ) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"); result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>");
return result; return result;
} }
@ -1171,7 +1173,7 @@ public class AcceptASDCController implements ServletContextAware {
st.close(); st.close();
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"); result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>");
return result; return result;
} }
@ -1180,7 +1182,7 @@ public class AcceptASDCController implements ServletContextAware {
if(exists) if(exists)
{ {
String sql="update main.frmlocust set\n" String sql="update main.frmlocust set\n"
+" uid = ?,\n" +" uid = main.strtouuid(?),\n"
+" changed = false,\n" +" changed = false,\n"
+" user_id=?,\n" +" user_id=?,\n"
+" device_id=?,\n" +" device_id=?,\n"
@ -1263,7 +1265,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()+" "+sql); logRotate(data_dir+"errors.log",ex.getMessage()+" "+sql);
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"); result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>");
return result; return result;
} }
@ -1349,7 +1351,7 @@ public class AcceptASDCController implements ServletContextAware {
+" geom,\n" +" geom,\n"
+" test\n" +" test\n"
+")values(\n" +")values(\n"
+" ?,\n" //1 uid +" main.strtouuid(?),\n" //1 uid
+" false,\n" +" false,\n"
+" ?,\n" //2 user_id +" ?,\n" //2 user_id
+" ?,\n" //3 device_id +" ?,\n" //3 device_id
@ -1432,7 +1434,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()+" "+sql); logRotate(data_dir+"errors.log",ex.getMessage()+" "+sql);
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"); result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>");
return result; return result;
} }
@ -1572,7 +1574,7 @@ public class AcceptASDCController implements ServletContextAware {
try{ try{
tm = new java.sql.Timestamp(dfm.parse(date).getTime()); tm = new java.sql.Timestamp(dfm.parse(date).getTime());
} catch (Exception ex) { } catch (Exception ex) {
logger.error("Error",ex.getMessage()); logger.error(ex.getMessage(), ex);
} }
stmt.setTimestamp(14, tm); stmt.setTimestamp(14, tm);
} }
@ -1688,7 +1690,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"); result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>");
return result; return result;
} }
@ -1698,7 +1700,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt.execute(); stmt.execute();
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex.getMessage()); logger.error(ex.getMessage(), ex);
result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"); result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>");
return result; return result;
} }
@ -1749,7 +1751,7 @@ public class AcceptASDCController implements ServletContextAware {
rs = st.executeQuery("select 1 from main.frmlocustdel where uid=main.strtouuid('"+uid+"')"); rs = st.executeQuery("select 1 from main.frmlocustdel where uid=main.strtouuid('"+uid+"')");
} catch( SQLException ex ) { } catch( SQLException ex ) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex.getMessage()); logger.error(ex.getMessage(), ex);
result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"); result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>");
return result; return result;
} }
@ -1883,7 +1885,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"); result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>");
return result; return result;
} }
@ -2110,7 +2112,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"); result=("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>");
return result; return result;
} }
@ -2275,7 +2277,7 @@ public class AcceptASDCController implements ServletContextAware {
try{ try{
tm = new java.sql.Timestamp(dfm.parse(date).getTime()); tm = new java.sql.Timestamp(dfm.parse(date).getTime());
} catch (Exception ex) { } catch (Exception ex) {
logger.error("Error",ex.getMessage()); logger.error(ex.getMessage(), ex);
} }
stmt.setTimestamp(14, tm); stmt.setTimestamp(14, tm);
} }
@ -2435,7 +2437,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"; result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>";
return result; return result;
} }
@ -2445,7 +2447,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt.execute(); stmt.execute();
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"; result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>";
return result; return result;
} }
@ -2490,13 +2492,13 @@ public class AcceptASDCController implements ServletContextAware {
} catch (Exception ex) { } catch (Exception ex) {
//logRotate(data_dir+"errors.log",ex.getMessage()); //logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
}finally { }finally {
if(conn!=null){ try{ conn.close(); }catch(Exception e){} } if(conn!=null){ try{ conn.close(); }catch(Exception e){} }
} }
return result; return result;
} }
@RequestMapping(value = "/get/",params = {"fn"},method = { RequestMethod.GET, RequestMethod.POST }) @RequestMapping(value = {"/get/", "/api/locust/v01/get/"},params = {"fn"},method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody @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) { 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) {
@ -2530,7 +2532,7 @@ public class AcceptASDCController implements ServletContextAware {
stm.close(); stm.close();
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"; result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>";
response.setContentType("application/xml"); response.setContentType("application/xml");
return result; return result;
@ -2542,7 +2544,7 @@ public class AcceptASDCController implements ServletContextAware {
{ {
//int pR=0; //int pR=0;
String pN=""; String pN="";
int pS=0; long pS=0;
//int pL=0; //int pL=0;
String val; String val;
@ -2550,7 +2552,7 @@ public class AcceptASDCController implements ServletContextAware {
//if(val!=null) pR=Integer.parseInt(val); //if(val!=null) pR=Integer.parseInt(val);
pN = reqN; pN = reqN;
val = reqS; val = reqS;
if(val!=null) pS=Integer.parseInt(val); if(val!=null) pS=Long.parseLong(val);
val = reqL; val = reqL;
//if(val!=null) pL=100; //if(val!=null) pL=100;
@ -2587,7 +2589,7 @@ public class AcceptASDCController implements ServletContextAware {
rs = st.executeQuery(sql); rs = st.executeQuery(sql);
} catch( SQLException ex ) { } catch( SQLException ex ) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<metadata fn=\"-1\"><![CDATA[SQL arror: "+ex.getMessage()+"]]></metadata>"; result="<metadata fn=\"-1\"><![CDATA[SQL arror: "+ex.getMessage()+"]]></metadata>";
response.setContentType("application/xml"); response.setContentType("application/xml");
return result; return result;
@ -2632,7 +2634,7 @@ public class AcceptASDCController implements ServletContextAware {
} }
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<metadata fn=\"-1\"><![CDATA[SQL arror: "+ex.getMessage()+"]]></metadata>"; result="<metadata fn=\"-1\"><![CDATA[SQL arror: "+ex.getMessage()+"]]></metadata>";
response.setContentType("application/xml"); response.setContentType("application/xml");
return result; return result;
@ -2647,7 +2649,7 @@ public class AcceptASDCController implements ServletContextAware {
String dataDir = data_dir; String dataDir = data_dir;
String tmpDir = "temp"+File.separator; String tmpDir = "temp"+File.separator;
try{ new File(dataDir+tmpDir).mkdirs(); }catch (Exception ex) { try{ new File(dataDir+tmpDir).mkdirs(); }catch (Exception ex) {
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>"; result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"-1\"><![CDATA["+ex.getMessage()+"]]></metadata>";
response.setContentType("application/xml"); response.setContentType("application/xml");
return result; return result;
@ -2674,7 +2676,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (Exception ex) { } catch (Exception ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
} }
result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"6\"><![CDATA[1]]></metadata>"; result="<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"6\"><![CDATA[1]]></metadata>";
}else }else
@ -2686,7 +2688,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (Exception ex) { } catch (Exception ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
}finally { }finally {
if(conn!=null) {try { conn.close(); } catch (SQLException e) {} } if(conn!=null) {try { conn.close(); } catch (SQLException e) {} }
} }
@ -2699,7 +2701,7 @@ public class AcceptASDCController implements ServletContextAware {
* @param reqData * @param reqData
* @return * @return
*/ */
@RequestMapping(value = "/asdc/tctable/",method = { RequestMethod.GET, RequestMethod.POST },produces = "application/octet-stream") @RequestMapping(value = {"/asdc/tctable/", "/api/locust/v01/asdc/tctable/"},method = { RequestMethod.GET, RequestMethod.POST },produces = "application/octet-stream")
@ResponseBody @ResponseBody
public Object uploadTCTable(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestParam(required=false,name="file") MultipartFile file) { public Object uploadTCTable(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestParam(required=false,name="file") MultipartFile file) {
@ -2754,7 +2756,7 @@ public class AcceptASDCController implements ServletContextAware {
rs = st.executeQuery(sql); rs = st.executeQuery(sql);
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -2783,7 +2785,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -2812,7 +2814,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -2828,7 +2830,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt.setString(7, tbl.fields.get(0).getStrVal()); stmt.setString(7, tbl.fields.get(0).getStrVal());
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -2839,7 +2841,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt.execute(); stmt.execute();
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -2847,7 +2849,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -2895,7 +2897,7 @@ public class AcceptASDCController implements ServletContextAware {
rs = st.executeQuery(sql); rs = st.executeQuery(sql);
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -2942,7 +2944,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -3000,7 +3002,7 @@ public class AcceptASDCController implements ServletContextAware {
stmt.setString(7, tbl.fields.get(0).getStrVal());*/ stmt.setString(7, tbl.fields.get(0).getStrVal());*/
} catch (SQLException ex) { } catch (SQLException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -3013,7 +3015,7 @@ public class AcceptASDCController implements ServletContextAware {
} }
} catch (IOException ex) { } catch (IOException ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -3021,7 +3023,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error("Error:",ex); logger.error(ex.getMessage(), ex);
result.put("error_code",1); result.put("error_code",1);
result.put("error_message", ex.getMessage()); result.put("error_message", ex.getMessage());
return result.toString(); return result.toString();
@ -3032,21 +3034,10 @@ public class AcceptASDCController implements ServletContextAware {
} }
//table=frmlocust&file=3a28b88f_locust_1508816625.jpg //table=frmlocust&file=3a28b88f_locust_1508816625.jpg
@RequestMapping(value = "/photo/",method = RequestMethod.GET, produces = "image/jpeg") @RequestMapping(value = {"/photo/", "/api/locust/v01/"},method = RequestMethod.GET, produces = "image/jpeg")
@ResponseBody @ResponseBody
public FileSystemResource sendPhoto(HttpServletResponse response,@RequestParam(required=true,name="table") String tableName,@RequestParam(required=true,name="file") String fileName) { public FileSystemResource sendPhoto(HttpServletResponse response,@RequestParam(required=true,name="table") String tableName,@RequestParam(required=true,name="file") String fileName) {
//Load DB configuration
String data_dir = "";
Properties prop = new Properties();
try {
prop.load(new FileInputStream("org_ccalm_main.properties")); // load a properties file
data_dir = prop.getProperty("data.dir");
} catch (Exception ex) {
ex.printStackTrace();
logger.error("Error load org_ccalm_main.properties",ex);
}
File file = new File(data_dir + "data/" + tableName + "/" + fileName); File file = new File(data_dir + "data/" + tableName + "/" + fileName);
if(file.exists()) if(file.exists())
{ {
@ -3068,9 +3059,9 @@ public class AcceptASDCController implements ServletContextAware {
} }
} }
//@RequestMapping(value = "/get",params = {"fn"},method = { RequestMethod.GET, RequestMethod.POST }) //@RequestMapping(value = {"/get", "/api/locust/v01/"},params = {"fn"},method = { RequestMethod.GET, RequestMethod.POST })
//Для проверки какие фото есть на сервере а каких нет чтобы удалить из имена фотографий которых нет в базе //Для проверки какие фото есть на сервере а каких нет чтобы удалить из имена фотографий которых нет в базе
@RequestMapping(value = "/photolist",method = RequestMethod.GET, produces = "text/html") @RequestMapping(value = {"/photolist", "/api/locust/v01/"},method = RequestMethod.GET, produces = "text/html")
@ResponseBody @ResponseBody
public Object getPhotoList() { public Object getPhotoList() {
@ -3106,7 +3097,7 @@ public class AcceptASDCController implements ServletContextAware {
rs = st.executeQuery(sql); rs = st.executeQuery(sql);
} catch( SQLException ex ) { } catch( SQLException ex ) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=ex.getMessage(); result=ex.getMessage();
return result; return result;
} }
@ -3154,7 +3145,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=ex.getMessage(); result=ex.getMessage();
return result; return result;
} }
@ -3169,7 +3160,7 @@ public class AcceptASDCController implements ServletContextAware {
rs = st.executeQuery(sql); rs = st.executeQuery(sql);
} catch( SQLException ex ) { } catch( SQLException ex ) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=ex.getMessage(); result=ex.getMessage();
return result; return result;
} }
@ -3217,7 +3208,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (SQLException ex) { } catch (SQLException ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=ex.getMessage(); result=ex.getMessage();
return result; return result;
} }
@ -3226,7 +3217,7 @@ public class AcceptASDCController implements ServletContextAware {
} catch (Exception ex) { } catch (Exception ex) {
logRotate(data_dir+"errors.log",ex.getMessage()); logRotate(data_dir+"errors.log",ex.getMessage());
logger.error("error",ex); logger.error(ex.getMessage(), ex);
}finally{ }finally{
if(conn!=null){ try{ conn.close(); }catch(Exception e){} } if(conn!=null){ try{ conn.close(); }catch(Exception e){} }
} }
@ -3281,7 +3272,7 @@ public class AcceptASDCController implements ServletContextAware {
}catch(Exception ex) }catch(Exception ex)
{ {
System.out.println(ex.getMessage()); System.out.println(ex.getMessage());
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
result=false; result=false;
} }
return result; return result;
@ -3306,7 +3297,7 @@ public class AcceptASDCController implements ServletContextAware {
writer.newLine(); writer.newLine();
writer.close(); writer.close();
} catch (IOException ex) { } catch (IOException ex) {
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
} }
} }
} }

View File

@ -65,7 +65,7 @@ public class AcceptEXCEL implements ServletContextAware {
this.context=context; this.context=context;
} }
@RequestMapping(value = "/AcceptCSV", method = { RequestMethod.GET, RequestMethod.POST }) @RequestMapping(value = {"/AcceptCSV", "/api/locust/v01/"}, 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) { public String acceptCSV(@ModelAttribute User user, Model model,@RequestParam(required=false,name="file") MultipartFile file,@RequestParam(required=false,name="skip",defaultValue = "0") Boolean skip) {
Connection conn = null; Connection conn = null;

File diff suppressed because it is too large Load Diff

View File

@ -64,7 +64,7 @@ public class DataJSON implements ServletContextAware {
// return new User("none"); // return new User("none");
//} //}
@RequestMapping(value = "/get_companies",method = {RequestMethod.POST,RequestMethod.GET}, produces = "application/json;charset=UTF-8") @RequestMapping(value = {"/get_companies", "/api/locust/v01/get_companies"},method = {RequestMethod.POST,RequestMethod.GET}, produces = "application/json;charset=UTF-8")
@ResponseBody @ResponseBody
public String getCompanies(@ModelAttribute User user,@RequestParam(required=false,name="country_id") String country_id,@RequestParam(required=false,name="lng") String language_id) { public String getCompanies(@ModelAttribute User user,@RequestParam(required=false,name="country_id") String country_id,@RequestParam(required=false,name="lng") String language_id) {

View File

@ -30,7 +30,7 @@ public class DownloadNDVI implements ServletContextAware {
private ServletContext context; private ServletContext context;
@RequestMapping(value = "/DownloadNDVI",method = RequestMethod.GET,produces = "text/html;charset=UTF-8") @RequestMapping(value = {"/DownloadNDVI", "/api/locust/v01/DownloadNDVI"},method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody @ResponseBody
public Object ajaxTamer(@RequestParam(required=false,name="forecast") String forecast) { public Object ajaxTamer(@RequestParam(required=false,name="forecast") String forecast) {
@ -62,6 +62,7 @@ public class DownloadNDVI implements ServletContextAware {
//String fullPath = context.getRealPath("/WEB-INF/config.xml"); //String fullPath = context.getRealPath("/WEB-INF/config.xml");
//File fXmlFile = new File(fullPath); //File fXmlFile = new File(fullPath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
//Document doc = dBuilder.parse(fXmlFile); //Document doc = dBuilder.parse(fXmlFile);
Document doc = dBuilder.parse(new ClassPathResource("config.xml").getInputStream()); Document doc = dBuilder.parse(new ClassPathResource("config.xml").getInputStream());

View File

@ -51,7 +51,7 @@ public class DownloadWeather implements ServletContextAware {
@Value("${data.dir}") @Value("${data.dir}")
String data_dir = ""; String data_dir = "";
@RequestMapping(value = "/DownloadWeather",method = RequestMethod.GET,produces = "text/html;charset=UTF-8") @RequestMapping(value = {"/DownloadWeather", "/api/locust/v01/DownloadWeather"},method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody @ResponseBody
public Object ajaxTamer(@RequestParam(required=false,name="forecast") String forecast,@RequestParam(required=false,name="date") String date) { 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". //String forecast = request.getParameter("forecast"); //Date like as "000".
@ -354,7 +354,7 @@ public class DownloadWeather implements ServletContextAware {
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
//List of "Soil temperature" dates from database in JSON //List of "Soil temperature" dates from database in JSON
@RequestMapping(value = "/WeatherSoilDates",method = RequestMethod.GET,produces = "text/html;charset=UTF-8") @RequestMapping(value = {"/WeatherSoilDates", "/api/locust/v01/WeatherSoilDates"},method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody @ResponseBody
public Object ajaxSoilDates() { public Object ajaxSoilDates() {
boolean error=false; boolean error=false;

View File

@ -47,7 +47,7 @@ public class GeoGSON implements ServletContextAware {
@Value("${data.dir}") @Value("${data.dir}")
String data_dir = ""; String data_dir = "";
@RequestMapping(value = "/geojson", method = RequestMethod.GET) @RequestMapping(value = {"/geojson", "/api/locust/v01/geojson"}, method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Object home(@RequestParam(required=false,name="table") String table,@RequestParam(required=false,name="id") String id) public Object home(@RequestParam(required=false,name="table") String table,@RequestParam(required=false,name="id") String id)
{ {
@ -110,7 +110,7 @@ public class GeoGSON implements ServletContextAware {
//For compilatin android project //For compilatin android project
//http://127.0.0.1:8080/CCALM/countriesregionspoints //http://127.0.0.1:8080/CCALM/countriesregionspoints
@RequestMapping(value = "/countriesregionspoints", method = RequestMethod.GET) @RequestMapping(value = {"/countriesregionspoints", "/api/locust/v01/countriesregionspoints"}, method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Object countriesregions() public Object countriesregions()
{ {

View File

@ -0,0 +1,48 @@
package org.ccalm.main;
import org.ccalm.main.models.ErrorResponseModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.util.UUID;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<ErrorResponseModel> handleNotFound(NoHandlerFoundException ex) {
ErrorResponseModel errorResponse = new ErrorResponseModel(
HttpStatus.NOT_FOUND.value(),
10000,
"Not_Found",
UUID.randomUUID().toString()
);
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponseModel> handleException(Exception ex) {
ErrorResponseModel errorResponse = new ErrorResponseModel(
HttpStatus.NOT_FOUND.value(),
10000,
"Internal_Server_Error", //Collections.singletonList("Internal_Server_Error"),
UUID.randomUUID().toString()
);
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@RequestMapping("/error")
public ResponseEntity<ErrorResponseModel> handleError() {
ErrorResponseModel errorResponse = new ErrorResponseModel(
HttpStatus.NOT_FOUND.value(),
10000,
"Unknown_error",
UUID.randomUUID().toString()
);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
}

View File

@ -58,7 +58,7 @@ public class Integration implements ServletContextAware {
@Value("${data.dir}") @Value("${data.dir}")
String data_dir = ""; String data_dir = "";
@RequestMapping(value = "/integration/getByTime", method = RequestMethod.GET,produces = "application/json; charset=utf-8") @RequestMapping(value = {"/integration/getByTime", "/api/locust/v01/integration/getByTime"}, method = RequestMethod.GET,produces = "application/json; charset=utf-8")
@ResponseBody @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) 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)
{ {
@ -68,7 +68,7 @@ public class Integration implements ServletContextAware {
return getData(token,timeBegin,timeEnd,null,null); return getData(token,timeBegin,timeEnd,null,null);
} }
@RequestMapping(value = "/integration/getByDate", method = RequestMethod.GET,produces = "application/json; charset=utf-8") @RequestMapping(value = {"/integration/getByDate", "/api/locust/v01/integration/getByDate"}, method = RequestMethod.GET,produces = "application/json; charset=utf-8")
@ResponseBody @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) 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)
{ {
@ -528,7 +528,7 @@ public class Integration implements ServletContextAware {
} }
@RequestMapping(value = "/integration/getPhoto", method = RequestMethod.GET,produces = "application/json; charset=utf-8") @RequestMapping(value = {"/integration/getPhoto", "/api/locust/v01/integration/getPhoto"}, method = RequestMethod.GET,produces = "application/json; charset=utf-8")
@ResponseBody @ResponseBody
public Object getPhoto(@RequestParam(required=true,name="token") String token,@RequestParam(required=true,name="id") Long id) public Object getPhoto(@RequestParam(required=true,name="token") String token,@RequestParam(required=true,name="id") Long id)
{ {

View File

@ -1,12 +1,10 @@
package org.ccalm.main; package org.ccalm.main;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.sql.*; import java.sql.*;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Properties; import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
//import javax.servlet.ServletContext; //import javax.servlet.ServletContext;
@ -21,7 +19,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.http.CacheControl; import org.springframework.http.CacheControl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@ -30,7 +27,6 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletContextAware; import org.springframework.web.context.ServletContextAware;
import org.ccalm.main.TranslationUtils;
import tools.DBTools; import tools.DBTools;
import tools.User; import tools.User;
@ -61,7 +57,7 @@ public class MainController implements ServletContextAware {
/** /**
* Simply selects the home view to render by returning its name. * Simply selects the home view to render by returning its name.
*/ */
@RequestMapping(value = "/privacy", method = RequestMethod.GET) @RequestMapping(value = {"/privacy", "/api/locust/v01/privacy"}, method = RequestMethod.GET)
public String privacy(Locale locale, Model model) { public String privacy(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale); logger.info("Welcome home! The client locale is {}.", locale);
@ -73,7 +69,7 @@ public class MainController implements ServletContextAware {
return "privacy"; return "privacy";
} }
@RequestMapping(value = "/robots.txt") @RequestMapping(value = {"/robots.txt", "/api/locust/v01/robots.txt"})
public void robots(HttpServletResponse response) { public void robots(HttpServletResponse response) {
try { try {
response.getWriter().write("User-agent: *\n"); response.getWriter().write("User-agent: *\n");
@ -87,7 +83,7 @@ public class MainController implements ServletContextAware {
} }
} }
@RequestMapping(value = "/sitemap.xml") @RequestMapping(value = {"/sitemap.xml", "/api/locust/v01/sitemap.xml"})
public void sitemap(HttpServletResponse response) { public void sitemap(HttpServletResponse response) {
try { try {
response.getWriter().write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" response.getWriter().write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
@ -104,7 +100,7 @@ public class MainController implements ServletContextAware {
/** /**
* Testing new main index page * Testing new main index page
*/ */
@RequestMapping(value = "/", method = RequestMethod.GET) @RequestMapping(value = {"/", "/api/locust/v01/"}, method = RequestMethod.GET)
public String home2(Model model,@CookieValue(value = "lng", defaultValue = "1") String language_id_str) { public String home2(Model model,@CookieValue(value = "lng", defaultValue = "1") String language_id_str) {
int language_id; int language_id;
try { try {
@ -120,12 +116,12 @@ public class MainController implements ServletContextAware {
//Для перевода выбираю всё что под номером 1 в переводе //Для перевода выбираю всё что под номером 1 в переводе
TranslationUtils.loadTranslations(jdbcTemplate, language_id, model); TranslationUtils.loadTranslations(jdbcTemplate, language_id, model);
//return "index"; return "index";
return "test"; //return "test";
} }
//Returns data for building a map on the first index page //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") @RequestMapping(value = {"/dataindex", "/api/locust/v01/dataindex"},method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json; charset=utf-8")
@ResponseBody @ResponseBody
public Object ajaxIndexData(HttpServletResponse response,@ModelAttribute User user,@RequestParam(required=false,name="date_start") String date_start,@RequestParam(required=false,name="date_end") String date_end, @RequestParam(required=false,name="lng") String language_id) { public Object ajaxIndexData(HttpServletResponse response,@ModelAttribute User user,@RequestParam(required=false,name="date_start") String date_start,@RequestParam(required=false,name="date_end") String date_end, @RequestParam(required=false,name="lng") String language_id) {
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue(); String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
@ -160,7 +156,7 @@ public class MainController implements ServletContextAware {
} }
} catch( DataAccessException ex ) } catch( DataAccessException ex )
{ {
logger.error("Error",ex); logger.error(ex.getMessage(), ex);
} }
result.put("Error_code", "0"); result.put("Error_code", "0");

View File

@ -5,32 +5,37 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.Connection; import java.security.KeyFactory;
import java.sql.DriverManager; import java.security.PublicKey;
import java.sql.PreparedStatement; import java.security.spec.X509EncodedKeySpec;
import java.sql.ResultSet; import java.sql.*;
import java.sql.SQLException; import java.util.*;
import java.sql.Statement;
import java.util.Properties;
//import javax.servlet.ServletContext; //import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import com.zaxxer.hikari.HikariDataSource;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.ServletContext; import jakarta.servlet.ServletContext;
import org.ccalm.main.models.ErrorResponseModel;
import org.ccalm.main.utils.CustomException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource; 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.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.*;
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.springframework.web.context.ServletContextAware;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
@ -40,7 +45,10 @@ import org.json.JSONObject;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import tctable.Tools;
import tools.DBTools;
import tools.PreparedStatementNamed; import tools.PreparedStatementNamed;
import tools.Translation;
import tools.User; import tools.User;
@Controller @Controller
@ -57,20 +65,52 @@ public class Products implements ServletContextAware {
String db_login=""; String db_login="";
@Value("${spring.datasource.password}") @Value("${spring.datasource.password}")
String db_password=""; String db_password="";
@Value("${public.key}")
String key_a_txt="";
private final NamedParameterJdbcTemplate jdbcTemplate;
private final Environment environment;
private HikariDataSource dataSource;
//If not created object "user", create him. //If not created object "user", create him.
//@ModelAttribute("user") //@ModelAttribute("user")
//public User populatePerson() { //public User populatePerson() {
// return new User("none"); // return new User("none");
//} //}
//---------------------------------------------------------------------------
@RequestMapping(value = "/get_survey",method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @Autowired
public Products(NamedParameterJdbcTemplate jdbcTemplate, HikariDataSource dataSource, Environment environment) {
this.jdbcTemplate = jdbcTemplate;
this.environment = environment;
this.dataSource = dataSource;
}
//---------------------------------------------------------------------------
@RequestMapping(value = {"/get_survey", "/api/locust/v01/get_survey"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody @ResponseBody
public String getLocustSurvey(@ModelAttribute User user,@RequestBody(required=false) byte[] reqData,@RequestParam(required=false,name="lng") String language_id) { public ResponseEntity<Object> getLocustSurvey(
@ModelAttribute User user,
int errorCode=0; @RequestBody(required=false) byte[] reqData,
String errorMessage=""; @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
Translation trt = new Translation(language_id,jdbcTemplate);
try{
if(user.id==null || user.id.equals("null")) {
if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) {
throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"), UUID.randomUUID().toString(),false);
}
Jws<Claims> claims = null;
PublicKey key_a = getPublicKey();
try {
claims = Jwts.parserBuilder()
.setSigningKey(key_a)
.build()
.parseClaimsJws(jwt_a);
} catch (Exception e) {
throw new CustomException(401, 10401, trt.trt(false, "JWT_token_verification_error"), UUID.randomUUID().toString(),false);
}
user.id = claims.getBody().get("user_id").toString();
}
Connection conn = null; Connection conn = null;
try { try {
@ -79,13 +119,10 @@ public class Products implements ServletContextAware {
if (conn != null) { if (conn != null) {
logger.info("Connect is OK!"); logger.info("Connect is OK!");
} else { } else {
errorCode=1; throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
errorMessage+="An error occurred while connecting to the database!";
} }
} catch (Exception ex) { } catch (Exception ex) {
logger.info(ex.getMessage()); throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
errorCode=1;
errorMessage+="An error occurred while connecting to the database!";
} }
try { try {
@ -94,9 +131,7 @@ public class Products implements ServletContextAware {
stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем раскоментил? может в начале поставить ещё TimeZone.setDefault(TimeZone.getTimeZone("UTC")); ? stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем раскоментил? может в начале поставить ещё TimeZone.setDefault(TimeZone.getTimeZone("UTC")); ?
stt0.close(); stt0.close();
} catch (SQLException ex) { } catch (SQLException ex) {
logger.info(ex.getMessage()); throw new CustomException(200, 10000, trt.trt(false, "Failed to execute SQL query!"), UUID.randomUUID().toString(),true);
errorCode=1;
errorMessage+="Failed to execute SQL query!";
} }
JSONObject doc=null; JSONObject doc=null;
@ -344,46 +379,66 @@ public class Products implements ServletContextAware {
} }
rs.close(); rs.close();
} catch (SQLException ex) { } catch (SQLException ex) {
errorCode=4; String uuid = UUID.randomUUID().toString();
errorMessage+="Internal server error, sampling."; logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
ex.printStackTrace(); throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
logger.info(ex.getMessage());
} }
} }
} catch (SQLException ex) { } catch (SQLException ex) {
errorCode=5; String uuid = UUID.randomUUID().toString();
errorMessage+="Внутренняя ошибка сервера, запрос. "; logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
ex.printStackTrace(); throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
logger.info(ex.getMessage());
}finally { }finally {
if(rs!=null) try{rs.close();}catch(SQLException ex){} if(rs!=null) try{rs.close();}catch(SQLException ex){}
if(stt!=null) try{stt.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(); JSONObject obj = new JSONObject();
obj.put("error_code",0); obj.put("error_code",0);
obj.put("error_message", ""); obj.put("error_message", "");
if(doc!=null) if(doc!=null)
obj.put("indicator",doc.getString("indicator")); obj.put("indicator",doc.getString("indicator"));
obj.put("data",array); obj.put("data",array);
return obj.toString(); return ResponseEntity.ok(obj.toString());
} catch (CustomException e) {
if(e.isSaveToLog()) {
logger.error(MarkerFactory.getMarker(e.getErrorMarker()), e.getMessage());
}
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage());
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
} @RequestMapping(value = {"/get_spray", "/api/locust/v01/get_spray"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@RequestMapping(value = "/get_spray",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody @ResponseBody
public String getSprayMonitoring(@ModelAttribute User user,@RequestBody byte[] reqData,@RequestParam(required=false,name="lng") String language_id) { public ResponseEntity<Object> getSprayMonitoring(
@ModelAttribute User user,
int errorCode=0; @RequestBody byte[] reqData,
String errorMessage=""; @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
Translation trt = new Translation(language_id,jdbcTemplate);
try{
if(user.id==null || user.id.equals("null")) {
if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) {
throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"), UUID.randomUUID().toString(),false);
}
Jws<Claims> claims = null;
PublicKey key_a = getPublicKey();
try {
claims = Jwts.parserBuilder()
.setSigningKey(key_a)
.build()
.parseClaimsJws(jwt_a);
} catch (Exception e) {
throw new CustomException(401, 10401, trt.trt(false, "JWT_token_verification_error"), UUID.randomUUID().toString(),false);
}
user.id = claims.getBody().get("user_id").toString();
}
Connection conn = null; Connection conn = null;
try { try {
@ -392,13 +447,10 @@ public class Products implements ServletContextAware {
if (conn != null) { if (conn != null) {
logger.info("Connect is OK!"); logger.info("Connect is OK!");
} else { } else {
errorCode=1; throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
errorMessage+="An error occurred while connecting to the database!";
} }
} catch (Exception ex) { } catch (Exception ex) {
logger.info(ex.getMessage()); throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
errorCode=1;
errorMessage+="An error occurred while connecting to the database!";
} }
try { try {
@ -407,9 +459,7 @@ public class Products implements ServletContextAware {
stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';");
stt0.close(); stt0.close();
} catch (SQLException ex) { } catch (SQLException ex) {
logger.info(ex.getMessage()); throw new CustomException(200, 10000, trt.trt(false, "Failed to execute SQL query!"), UUID.randomUUID().toString(),true);
errorCode=1;
errorMessage+="Failed to execute SQL query!";
} }
JSONObject doc=null; JSONObject doc=null;
@ -625,43 +675,150 @@ public class Products implements ServletContextAware {
} }
rs.close(); rs.close();
} catch (SQLException ex) { } catch (SQLException ex) {
errorCode=4; String uuid = UUID.randomUUID().toString();
errorMessage+="Internal server error, sampling."; logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
ex.printStackTrace(); throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
logger.info(ex.getMessage());
} }
} }
} catch (SQLException ex) { } catch (SQLException ex) {
errorCode=5; throw new CustomException(200, 10000, trt.trt(false, "Internal server error."), UUID.randomUUID().toString(),true);
errorMessage+="Внутренняя ошибка сервера, запрос. ";
ex.printStackTrace();
logger.info(ex.getMessage());
}finally { }finally {
if(rs!=null) try{rs.close();}catch(SQLException ex){} if(rs!=null) try{rs.close();}catch(SQLException ex){}
if(stt!=null) try{stt.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(); JSONObject obj = new JSONObject();
obj.put("error_code",0); obj.put("error_code",0);
obj.put("error_message", ""); obj.put("error_message", "");
obj.put("data",array); obj.put("data",array);
return obj.toString(); return ResponseEntity.ok(obj.toString());
} catch (CustomException e) {
if(e.isSaveToLog()) {
logger.error(MarkerFactory.getMarker(e.getErrorMarker()), e.getMessage());
}
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage());
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@RequestMapping(value = "/get_checkpoints",method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @RequestMapping(value = { "/api/locust/v01/get_health"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody @ResponseBody
public String getCheckpoints(@ModelAttribute User user,@RequestBody byte[] reqData,@RequestParam(required=false,name="lng") String language_id) { public ResponseEntity<Object> getHealthPoints(
@ModelAttribute User user,
@RequestBody byte[] reqData,
@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
Translation trt = new Translation(language_id,jdbcTemplate);
try{
if(user.id==null || user.id.equals("null")) {
if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) {
throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"), UUID.randomUUID().toString(),false);
}
Jws<Claims> claims = null;
PublicKey key_a = getPublicKey();
try {
claims = Jwts.parserBuilder()
.setSigningKey(key_a)
.build()
.parseClaimsJws(jwt_a);
} catch (Exception e) {
throw new CustomException(401, 10401, trt.trt(false, "JWT_token_verification_error"), UUID.randomUUID().toString(),false);
}
user.id = claims.getBody().get("user_id").toString();
}
int errorCode=0; JSONObject doc=null;
String errorMessage=""; InputStream body;
if(reqData!=null) {
body = new ByteArrayInputStream(reqData);
String text="";
try {
text = new String(body.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException ex) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), ex.getMessage(), ex);
}
doc = new JSONObject(text);
}
JSONArray array=new JSONArray(); //Resulting data set
String sql_query = """
select
fld.uid,
fld.lat_center,
fld.lon_center,
ST_AsGeoJSON(fld.geom) as geom
from
main.frmlocusthealth flh
join main.frmlocustdel fld on fld.uid=flh.frmlocustdel_uid
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)
order by fld.id desc;
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
if(doc!=null) {
if(doc.isNull("country_id")) { parameters.addValue("country_id", null, Types.INTEGER); }
else { parameters.addValue("country_id", doc.getInt("country_id"), Types.INTEGER); }
}
List<String> ret = jdbcTemplate.query(sql_query, parameters, new DBTools.JsonRowMapper());
List<Map<String,String>> data = new ArrayList<>();
for (String s : ret) {
JSONObject row = new JSONObject(s);
array.put(row);
}
JSONObject obj = new JSONObject();
obj.put("error_code",0);
obj.put("error_message", "");
obj.put("data",array);
return ResponseEntity.ok(obj.toString());
} catch (CustomException e) {
if(e.isSaveToLog()) {
logger.error(MarkerFactory.getMarker(e.getErrorMarker()), e.getMessage());
}
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage());
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(value = {"/get_checkpoints", "/api/locust/v01/get_checkpoints"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<Object> getCheckpoints(
@ModelAttribute User user,
@RequestBody byte[] reqData,
@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
Translation trt = new Translation(language_id,jdbcTemplate);
try{
if(user.id==null || user.id.equals("null")) {
if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) {
throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"), UUID.randomUUID().toString(),false);
}
Jws<Claims> claims = null;
PublicKey key_a = getPublicKey();
try {
claims = Jwts.parserBuilder()
.setSigningKey(key_a)
.build()
.parseClaimsJws(jwt_a);
} catch (Exception e) {
throw new CustomException(401, 10401, trt.trt(false, "JWT_token_verification_error"), UUID.randomUUID().toString(),false);
}
user.id = claims.getBody().get("user_id").toString();
}
Connection conn = null; Connection conn = null;
try { try {
@ -670,13 +827,10 @@ public class Products implements ServletContextAware {
if (conn != null) { if (conn != null) {
logger.info("Connect is OK!"); logger.info("Connect is OK!");
} else { } else {
errorCode=1; throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
errorMessage+="An error occurred while connecting to the database!";
} }
} catch (Exception ex) { } catch (Exception ex) {
logger.info(ex.getMessage()); throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
errorCode=1;
errorMessage+="An error occurred while connecting to the database!";
} }
try { try {
@ -685,9 +839,7 @@ public class Products implements ServletContextAware {
stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';");
stt0.close(); stt0.close();
} catch (SQLException ex) { } catch (SQLException ex) {
logger.info(ex.getMessage()); throw new CustomException(200, 10000, trt.trt(false, "Failed to execute SQL query!"), UUID.randomUUID().toString(),true);
errorCode=1;
errorMessage+="Failed to execute SQL query!";
} }
JSONObject doc=null; JSONObject doc=null;
@ -727,7 +879,8 @@ public class Products implements ServletContextAware {
f.lon, f.lon,
f.radius, f.radius,
f.name, f.name,
f.temperature f.temperature_soil,
f.temperature_air
from from
main.frmcheckpoints f main.frmcheckpoints f
left join main._users u on u.id=f.user_id left join main._users u on u.id=f.user_id
@ -762,227 +915,189 @@ public class Products implements ServletContextAware {
obj.put("lat", lat); obj.put("lat", lat);
obj.put("lon", lon); obj.put("lon", lon);
obj.put("radius", rs.getFloat("radius")); obj.put("radius", rs.getFloat("radius"));
obj.put("temperature", rs.getFloat("temperature")); obj.put("temperature_soil", rs.getFloat("temperature_soil"));
obj.put("temperature_air", rs.getFloat("temperature_air"));
array.put(obj); array.put(obj);
} }
rs.close(); rs.close();
} catch (SQLException ex) { } catch (SQLException ex) {
errorCode=4; String uuid = UUID.randomUUID().toString();
errorMessage+="Internal server error, sampling."; logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
ex.printStackTrace(); throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
logger.info(ex.getMessage());
} }
} }
} catch (SQLException ex) { } catch (SQLException ex) {
errorCode=5; String uuid = UUID.randomUUID().toString();
errorMessage+="Internal server error, sampling. "; logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
ex.printStackTrace(); throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
logger.info(ex.getMessage());
}finally { }finally {
if(rs!=null) try{rs.close();}catch(SQLException ex){} if(rs!=null) try{rs.close();}catch(SQLException ex){}
if(stt!=null) try{stt.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(); JSONObject obj = new JSONObject();
obj.put("error_code",0); obj.put("error_code",0);
obj.put("error_message", ""); obj.put("error_message", "");
obj.put("data",array); obj.put("data",array);
return obj.toString(); return ResponseEntity.ok(obj.toString());
} catch (CustomException e) {
if(e.isSaveToLog()) {
logger.error(MarkerFactory.getMarker(e.getErrorMarker()), e.getMessage());
}
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage());
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
//Получить плотность личинок за последние 5 лет в заданном радиусе //Получить плотность личинок за последние 5 лет в заданном радиусе
@RequestMapping(value = "/get_density_larval",method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @RequestMapping(value = {"/get_density_larval", "/api/locust/v01/get_density_larval"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody @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) { public ResponseEntity<Object> getDensityLarval(
int errorCode=0; @ModelAttribute User user,
String errorMessage=""; @RequestBody byte[] reqData,
@RequestParam(required=false,name="id") Integer id,
Connection conn = null; @CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
Translation trt = new Translation(language_id,jdbcTemplate);
try{ try{
Class.forName("org.postgresql.Driver"); if(user.id==null || user.id.equals("null")) {
conn = DriverManager.getConnection(db_url, db_login, db_password); if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) {
if (conn != null) { throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"), UUID.randomUUID().toString(),false);
logger.info("Connect is OK!");
} else {
errorCode=1;
errorMessage+="An error occurred while connecting to the database!";
} }
} catch (Exception ex) { Jws<Claims> claims = null;
logger.info(ex.getMessage()); PublicKey key_a = getPublicKey();
errorCode=1;
errorMessage+="An error occurred while connecting to the database!";
}
try { try {
Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); claims = Jwts.parserBuilder()
stt0.executeUpdate("SET TIME ZONE 'UTC';"); //зачем коментил? .setSigningKey(key_a)
//stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем нужно вообще? .build()
stt0.close(); .parseClaimsJws(jwt_a);
} catch (SQLException ex) { } catch (Exception e) {
logger.info(ex.getMessage()); throw new CustomException(401, 10401, trt.trt(false, "JWT_token_verification_error"), UUID.randomUUID().toString(),false);
errorCode=1; }
errorMessage+="Failed to execute SQL query!"; user.id = claims.getBody().get("user_id").toString();
} }
JSONArray array=new JSONArray(); //Результирующий набор данных JSONArray array=new JSONArray(); //Результирующий набор данных
String sql_query = """
String sql_query = ""; select * from main.get_density_larval(:id);
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); MapSqlParameterSource parameters = new MapSqlParameterSource();
stmtn.setInt("id",id); parameters.addValue("id", id);
PreparedStatement stmt=stmtn.getPreparedStatement(); List<String> ret = jdbcTemplate.query(sql_query, parameters, new DBTools.JsonRowMapper());
List<Map<String,String>> data = new ArrayList<>();
rs = stmt.executeQuery(); for (String s : ret) {
if (rs != null) { JSONObject row = new JSONObject(s);
try { array.put(row);
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="";
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(); JSONObject obj = new JSONObject();
obj.put("error_code",0); obj.put("error_code",0);
obj.put("error_message", ""); obj.put("error_message", "");
obj.put("data",array); obj.put("data",array);
return obj.toString(); return ResponseEntity.ok(obj.toString());
} catch (CustomException e) {
if(e.isSaveToLog()) {
logger.error(MarkerFactory.getMarker(e.getErrorMarker()), e.getMessage());
}
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage());
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
//Получить плотность имаго за последние 5 лет
@RequestMapping(value = {"/get_density_imago", "/api/locust/v01/get_density_imago"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<Object> getDensityImago(
@ModelAttribute User user,
@RequestParam(required=false,name="id") Integer id,
@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
Translation trt = new Translation(language_id,jdbcTemplate);
try{
if(user.id==null || user.id.equals("null")) {
if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) {
throw new CustomException(401, 10401, trt.trt(false, "Please_log_in"), UUID.randomUUID().toString(),false);
}
Jws<Claims> claims = null;
PublicKey key_a = getPublicKey();
try {
claims = Jwts.parserBuilder()
.setSigningKey(key_a)
.build()
.parseClaimsJws(jwt_a);
} catch (Exception e) {
throw new CustomException(401, 10401, trt.trt(false, "JWT_token_verification_error"), UUID.randomUUID().toString(),false);
}
user.id = claims.getBody().get("user_id").toString();
}
JSONArray array=new JSONArray(); //Результирующий набор данных
String sql_query = """
select * from main.get_density_imago(:id);
""";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("id", id);
List<String> ret = jdbcTemplate.query(sql_query, parameters, new DBTools.JsonRowMapper());
List<Map<String,String>> data = new ArrayList<>();
for (String s : ret) {
JSONObject row = new JSONObject(s);
array.put(row);
}
JSONObject obj = new JSONObject();
obj.put("error_code",0);
obj.put("error_message", "");
obj.put("data",array);
return ResponseEntity.ok(obj.toString());
} catch (CustomException e) {
if(e.isSaveToLog()) {
logger.error(MarkerFactory.getMarker(e.getErrorMarker()), e.getMessage());
}
return new ResponseEntity<>(e.getErrorResponseModel(), getHttpStatus(e.getHttpCode()));
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage());
return new ResponseEntity<>(new ErrorResponseModel(500, 10000, trt.trt(false, "Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
//---------------------------------------------------------------------------
@Override @Override
public void setServletContext(ServletContext servletContext) { public void setServletContext(ServletContext servletContext) {
this.context=servletContext; this.context=servletContext;
} }
//---------------------------------------------------------------------------
public static HttpStatus getHttpStatus(int code) {
try {
return HttpStatus.valueOf(code);
} catch (IllegalArgumentException ex) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
//---------------------------------------------------------------------------
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) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage());
}
return null;
}
//---------------------------------------------------------------------------
} }

View File

@ -66,7 +66,7 @@ public class QGIS implements ServletContextAware {
// return new User("none"); // return new User("none");
//} //}
@RequestMapping(value = "/QGIS",method = RequestMethod.GET,produces = "application/octet-stream") @RequestMapping(value = {"/QGIS", "/api/locust/v01/QGIS"},method = RequestMethod.GET,produces = "application/octet-stream")
@ResponseBody @ResponseBody
public HttpEntity<byte[]> ajaxTamer(@ModelAttribute User user, @RequestParam(required=false,name="day") String day, @RequestParam(required=false,name="name") String name, @RequestParam(required=false,name="time") String time, @RequestParam(required=false,name="time_start") String time_start, @RequestParam(required=false,name="time_end") String time_end, @RequestParam(required=false,name="country_id") String country_id, @RequestParam(required=false,name="locust_type_id") String locust_type_id, @RequestParam(required=false,name="date_start") String date_start, @RequestParam(required=false,name="date_end") String date_end, @RequestParam(required=false,name="registered") String registered, @RequestParam(required=false,name="year") String year, @RequestParam(required=false,name="region_id") String region_id, @RequestParam(required=false,name="country_name") String country_name, @RequestParam(required=false,name="lng") String language_id, HttpServletResponse response) public HttpEntity<byte[]> ajaxTamer(@ModelAttribute User user, @RequestParam(required=false,name="day") String day, @RequestParam(required=false,name="name") String name, @RequestParam(required=false,name="time") String time, @RequestParam(required=false,name="time_start") String time_start, @RequestParam(required=false,name="time_end") String time_end, @RequestParam(required=false,name="country_id") String country_id, @RequestParam(required=false,name="locust_type_id") String locust_type_id, @RequestParam(required=false,name="date_start") String date_start, @RequestParam(required=false,name="date_end") String date_end, @RequestParam(required=false,name="registered") String registered, @RequestParam(required=false,name="year") String year, @RequestParam(required=false,name="region_id") String region_id, @RequestParam(required=false,name="country_name") String country_name, @RequestParam(required=false,name="lng") String language_id, HttpServletResponse response)
{ {
@ -417,7 +417,7 @@ public class QGIS implements ServletContextAware {
public String fileToString(String fName) public String fileToString(String fName)
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder(1024);
try try
{ {
InputStream is = new FileInputStream(fName); InputStream is = new FileInputStream(fName);

View File

@ -67,7 +67,7 @@ public class SendMail implements ServletContextAware {
// return new User("none"); // return new User("none");
//} //}
@RequestMapping(value = "/SendMail",method = RequestMethod.GET,produces = "text/html;charset=UTF-8") @RequestMapping(value = {"/SendMail", "/api/locust/v01/SendMail"},method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody @ResponseBody
public Object send(@ModelAttribute User user,@RequestParam(required=false,name="lng") String language_id) { public Object send(@ModelAttribute User user,@RequestParam(required=false,name="lng") String language_id) {

View File

@ -3,6 +3,7 @@ package org.ccalm.main;
import jakarta.servlet.ServletContext; import jakarta.servlet.ServletContext;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*; import org.springframework.http.*;
@ -47,7 +48,7 @@ public class SendWarning {
this.jdbcTemplate = jdbcTemplate; this.jdbcTemplate = jdbcTemplate;
} }
public JSONObject getSoilTemperature(double lat,double lon){ public JSONObject getAirTemperature(double lat,double lon){
JSONObject result=null; JSONObject result=null;
// Формируем JSON-запрос // Формируем JSON-запрос
Map<String, Object> request = new HashMap<>(); Map<String, Object> request = new HashMap<>();
@ -71,14 +72,46 @@ public class SendWarning {
result.put("value", value); result.put("value", value);
} }
} }
} catch (Exception e) { } catch (Exception ex) {
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
logger.error(uuid,e); logger.error(MarkerFactory.getMarker(uuid),ex.getMessage(), ex);
} }
return result; return result;
} }
@RequestMapping(value = "/api/main/v01/SendWarning",method = RequestMethod.GET,produces = "application/json;charset=UTF-8") public JSONObject getSoilTemperature(double lat,double lon){
JSONObject result=null;
// Формируем JSON-запрос
Map<String, Object> request = new HashMap<>();
request.put("date", null); //NULL to select the latest date available in the database
request.put("hours", 0);
request.put("lon", lon);
request.put("lat", lat);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);
String url = "https://geoserver2.ccalm.org/geodatalist/getSoilTemperature";
try {
ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
Object date = response.getBody().get("date");
Object value = response.getBody().get("value");
if (value != null && date != null) {
result = new JSONObject();
result.put("date", date);
result.put("value", value);
}
}
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e);
}
return result;
}
//https://ccalm.org/api/locust/v01/SendWarning
@RequestMapping(value = {"/api/locust/v01/SendWarning"},method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
@ResponseBody @ResponseBody
public ResponseEntity<Object> send() { public ResponseEntity<Object> send() {
Map<String, Object> result = new HashMap<>(); Map<String, Object> result = new HashMap<>();
@ -91,38 +124,42 @@ public class SendWarning {
t.user_uid, t.user_uid,
t.lat, t.lat,
t.lon, t.lon,
t.temperature as value,
u.email, u.email,
l.short_name l.short_name,
t.temperature_air,
t.warn_air,
t.temperature_soil,
t.warn_soil
from from
main.frmcheckpoints t main.frmcheckpoints t
join main._users u on u.uid=t.user_uid join main._users u on u.uid=t.user_uid
join main._languages l on l.uid=u.language_uid join main._languages l on l.uid=u.language_uid
where where
t.del=false t.del=false
and t.warn=true and (t.warn_soil=true or t.warn_air=true)
"""; """;
MapSqlParameterSource parameters = new MapSqlParameterSource(); MapSqlParameterSource parameters = new MapSqlParameterSource();
//parameters.addValue("language_id", language_id, Types.INTEGER); //parameters.addValue("language_id", language_id, Types.INTEGER);
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
for (String jsonString : ret) { for (String jsonString : ret) {
JSONObject obj = new JSONObject(jsonString); JSONObject obj = new JSONObject(jsonString);
JSONObject tmp = getSoilTemperature(obj.getDouble("lat"),obj.getDouble("lon"));
if(tmp!=null) {
Translation trt=new Translation(obj.getString("short_name"),jdbcTemplate);
double value = obj.getDouble("value");
if (value < tmp.getDouble("value")) {
String email = obj.getString("email");
if(email.equals("irigm@mail.ru") || email.equals("ivanov.i@istt.kz")){ //TODO для тестирования потом удалить
StringBuilder html = new StringBuilder(); JSONObject tmp_air = getAirTemperature(obj.getDouble("lat"),obj.getDouble("lon"));
JSONObject tmp_soil = getSoilTemperature(obj.getDouble("lat"),obj.getDouble("lon"));
if(tmp_air!=null && obj.getBoolean("warn_air")) {
Translation trt=new Translation(obj.getString("short_name"),jdbcTemplate);
double value = obj.getDouble("temperature_air");
if (value < tmp_air.getDouble("value")) {
String email = obj.getString("email");
StringBuilder html = new StringBuilder(1024);
html.append("<html>") html.append("<html>")
.append("<head>") .append("<head>")
.append("<style>") .append("<style>")
.append("body { font-family: Arial, sans-serif; background-color: #f4f4f4; color: #333; margin: 0; padding: 0; }") .append("body { font-family: Arial, sans-serif; background-color: #f4f4f4; color: #333; margin: 0; padding: 0; }")
.append(".container { max-width: 600px; margin: 0 auto; padding: 20px; background-color: #fff; border: 1px solid #ddd; position: relative; }") .append(".container { max-width: 600px; margin: 20px auto 0 auto; padding: 20px; background-color: #fff; border: 1px solid #ddd; position: relative; }")
.append(".logo { position: absolute; top: 10px; right: 10px; width: 100px; height: auto; }") .append(".logo { position: absolute; top: 10px; right: 10px; width: 100px; height: auto; }")
.append("h2 { color: #d9534f; margin-top: 50px; }") // Отступ для логотипа .append("h2 { color: #d9534f; }")
.append("table { border-collapse: collapse; width: 100%; margin: 20px 0; }") .append("table { border-collapse: collapse; width: 100%; margin: 20px 0; }")
.append("th, td { padding: 10px; border: 1px solid #ddd; text-align: left; }") .append("th, td { padding: 10px; border: 1px solid #ddd; text-align: left; }")
.append("th { background-color: #f9f9f9; }") .append("th { background-color: #f9f9f9; }")
@ -131,21 +168,20 @@ public class SendWarning {
.append("</head>") .append("</head>")
.append("<body>") .append("<body>")
.append("<div class='container'>") .append("<div class='container'>")
.append("<img src='https://ccalm.org/resources/images/locust.png' alt='Logo' class='logo'>") // Логотип .append("<h2>").append(trt.trt(true,"Warning")).append("</h2>")
.append("<h2>").append(trt.trt("Warning")).append("</h2>") .append("<p>").append(trt.trt(true,"The_soil_temperature_has_exceeded_the_set_value")).append(": ").append(value).append("</p>")
.append("<p>").append(trt.trt("The_soil_temperature_has_exceeded_the_set_value")).append(": ").append(value).append("</p>")
.append("<table>") .append("<table>")
.append("<tr><th>").append(trt.trt("Date")).append("</th><td>").append(tmp.getString("date")).append("</td></tr>") .append("<tr><th>").append(trt.trt(true,"Date")).append("</th><td>").append(tmp_air.getString("date")).append("</td></tr>")
.append("<tr><th>").append(trt.trt("Value")).append("</th><td>").append(tmp.getDouble("value")).append(" °C</td></tr>") .append("<tr><th>").append(trt.trt(true,"Value")).append("</th><td>").append(tmp_air.getDouble("value")).append(" °C</td></tr>")
.append("</table>") .append("</table>")
.append(trt.trt("To_resume_monitoring_please_set_the_warn_field_to_true")) .append(trt.trt(true,"To_resume_monitoring_please_set_the_warn_field_to_true"))
.append("</div>") // Закрываем контейнер .append("</div>") // Закрываем контейнер
.append("</body>") .append("</body>")
.append("</html>"); .append("</html>");
boolean send = false; boolean send = false;
try { try {
EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, email, trt.trt("Soil temperature"), html.toString()); EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, email, trt.trt(true,"Air temperature"), html.toString());
send = true; send = true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -155,22 +191,78 @@ public class SendWarning {
update update
main.frmcheckpoints main.frmcheckpoints
set set
warn=true warn_air=false
where uid=:uid where uid=CAST(:uid AS uuid)
"""; """;
MapSqlParameterSource param = new MapSqlParameterSource(); MapSqlParameterSource param = new MapSqlParameterSource();
param.addValue("uid", obj.getString("uid"), Types.INTEGER); param.addValue("uid", obj.getString("uid"), Types.VARCHAR);
int rowsUpdated = jdbcTemplate.update(sql, param);
System.out.println("rowsUpdated = "+String.valueOf(rowsUpdated));
}
}
}
if(tmp_soil!=null && obj.getBoolean("warn_soil")) {
Translation trt=new Translation(obj.getString("short_name"),jdbcTemplate);
double value = obj.getDouble("temperature_soil");
if (value < tmp_soil.getDouble("value")) {
String email = obj.getString("email");
StringBuilder html = new StringBuilder(1024);
html.append("<html>")
.append("<head>")
.append("<style>")
.append("body { font-family: Arial, sans-serif; background-color: #f4f4f4; color: #333; margin: 0; padding: 0; }")
.append(".container { max-width: 600px; margin: 20px auto 0 auto; padding: 20px; background-color: #fff; border: 1px solid #ddd; position: relative; }")
.append(".logo { position: absolute; top: 10px; right: 10px; width: 100px; height: auto; }")
.append("h2 { color: #d9534f; }")
.append("table { border-collapse: collapse; width: 100%; margin: 20px 0; }")
.append("th, td { padding: 10px; border: 1px solid #ddd; text-align: left; }")
.append("th { background-color: #f9f9f9; }")
.append("p { font-weight: bold; }")
.append("</style>")
.append("</head>")
.append("<body>")
.append("<div class='container'>")
.append("<h2>").append(trt.trt(true,"Warning")).append("</h2>")
.append("<p>").append(trt.trt(true,"The_soil_temperature_has_exceeded_the_set_value")).append(": ").append(value).append("</p>")
.append("<table>")
.append("<tr><th>").append(trt.trt(true,"Date")).append("</th><td>").append(tmp_soil.getString("date")).append("</td></tr>")
.append("<tr><th>").append(trt.trt(true,"Value")).append("</th><td>").append(tmp_soil.getDouble("value")).append(" °C</td></tr>")
.append("</table>")
.append(trt.trt(true,"To_resume_monitoring_please_set_the_warn_field_to_true"))
.append("</div>") // Закрываем контейнер
.append("</body>")
.append("</html>");
boolean send = false;
try {
EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, email, trt.trt(true,"Soil temperature"), html.toString());
send = true;
} catch (Exception e) {
e.printStackTrace();
}
if(send) {
sql= """
update
main.frmcheckpoints
set
warn_soil=false
where uid=CAST(:uid AS uuid)
""";
MapSqlParameterSource param = new MapSqlParameterSource();
param.addValue("uid", obj.getString("uid"), Types.VARCHAR);
int rowsUpdated = jdbcTemplate.update(sql, param); int rowsUpdated = jdbcTemplate.update(sql, param);
System.out.println("rowsUpdated = "+String.valueOf(rowsUpdated)); System.out.println("rowsUpdated = "+String.valueOf(rowsUpdated));
} }
} }
} }
} }
} } catch (Exception ex) {
} catch (Exception e) {
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
logger.error(uuid,e); logger.error(MarkerFactory.getMarker(uuid),ex.getMessage(), ex);
} }
return new ResponseEntity<>(result, HttpStatus.OK); return new ResponseEntity<>(result, HttpStatus.OK);
} }
} }

View File

@ -23,7 +23,7 @@ public class SessionController {
// return new User("none"); // return new User("none");
//} //}
@RequestMapping(value = "/session", method = {RequestMethod.GET, RequestMethod.POST },produces = "application/json; charset=utf-8") @RequestMapping(value = {"/session", "/api/locust/v01/session"}, method = {RequestMethod.GET, RequestMethod.POST },produces = "application/json; charset=utf-8")
@ResponseBody @ResponseBody
public Object ajaxTest(@ModelAttribute User user) { public Object ajaxTest(@ModelAttribute User user) {

View File

@ -0,0 +1,14 @@
package org.ccalm.main;
import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.ThrowableProxyUtil;
public class SingleLineThrowableProxyConverter extends ThrowableProxyConverter {
@Override
protected String throwableProxyToString(IThrowableProxy tp) {
if (tp == null) return "";
String stackTrace = ThrowableProxyUtil.asString(tp);
return stackTrace.replace("\r", "").replace("\n", "\\n").replace("\t", " ");
}
}

View File

@ -0,0 +1,23 @@
package org.ccalm.main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContext implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(SpringContext.class);
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
context = applicationContext;
logger.warn("App is start");
}
public static ApplicationContext getApplicationContext() {
return context;
}
}

View File

@ -33,7 +33,7 @@ public class TestFiles implements ServletContextAware {
private ServletContext context; private ServletContext context;
@RequestMapping(value = "/TestFiles",method = RequestMethod.GET,produces = "text/html;charset=UTF-8") @RequestMapping(value = {"/TestFiles", "/api/locust/v01/TestFiles"},method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody @ResponseBody
public Object ajaxTamer() public Object ajaxTamer()
{ {

View File

@ -42,7 +42,7 @@ public class TranslationController implements ServletContextAware {
/** /**
* Simply selects the home view to render by returning its name. * Simply selects the home view to render by returning its name.
*/ */
@RequestMapping(value = "/translation", method = RequestMethod.GET) @RequestMapping(value = {"/translation", "/api/locust/v01/translation"}, method = RequestMethod.GET)
@ResponseBody @ResponseBody
public String home( public String home(
Model model, Model model,
@ -89,14 +89,13 @@ public class TranslationController implements ServletContextAware {
} }
/** /**
* Функция для получения переводов в формате JSON. * Function for get translation in JSON format
*/ */
@GetMapping(value = "/api/translation", produces = "application/json") @GetMapping(value = {"/api/translation", "/api/locust/v01/translation"}, produces = "application/json")
@ResponseBody @ResponseBody
public Map<String, String> getTranslations( public Map<String, String> getTranslations(
@CookieValue(value = "lng", defaultValue = "1") String language_id @CookieValue(value = "lng", defaultValue = "1") String language_id
) { ) {
Map<String, String> translations = new HashMap<>(); Map<String, String> translations = new HashMap<>();
try { try {

View File

@ -0,0 +1,432 @@
package org.ccalm.main;
import org.ccalm.main.models.FrmLocustModel;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import tools.DBTools;
import java.sql.Types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class UpdateLocust {
private static final Logger logger = LoggerFactory.getLogger(UpdateLocust.class);
private final NamedParameterJdbcTemplate jdbcTemplate;
UpdateLocust(NamedParameterJdbcTemplate jdbcTemplate){
this.jdbcTemplate = jdbcTemplate;
}
//Update or insert locust survey form
public boolean update(FrmLocustModel locust){
String sql;
boolean exists=false; //Is there a record.
MapSqlParameterSource parameters;
//Если данные пришли из внешнего источника то выбираю uid по eid
if(locust.eid!=null && locust.uid==null) {
int year = locust.date.toLocalDateTime().getYear();
sql = """
select uid from main.frmlocust where eid=:eid and company_uid=CAST(:company_uid AS uuid) and EXTRACT(YEAR FROM date)=:year
""";
parameters = new MapSqlParameterSource();
parameters.addValue("eid", locust.eid, Types.BIGINT);
parameters.addValue("company_uid", locust.company_uid, Types.VARCHAR);
parameters.addValue("year", year, Types.INTEGER);
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
for (String s : ret) {
JSONObject obj = new JSONObject(s);
if(!obj.isNull("uid")) {
locust.uid = obj.getString("uid");
exists=true;
}
}
}
//Check exist record by uid
sql= """
select uid from main.frmlocust where uid=CAST(:uid AS uuid);
""";
parameters = new MapSqlParameterSource();
parameters.addValue("uid", locust.uid, Types.VARCHAR);
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
for (String s : ret) {
exists=true;
}
if(exists)
{
sql= """
update main.frmlocust set
eid=:eid,
changed = false,
company_uid=CAST(:company_uid AS uuid),
user_id=:user_id,
device_id=:device_id,
image_name1=:image_name1,
image_name2=:image_name2,
image_name3=:image_name3,
country_id=:country_id,
region_id=:region_id,
area=:area,
district=:district,
village=:village,
terrain=:terrain,
observer=:observer,
date=:date,
timezone=CAST(:timezone AS interval),
lat_center=:lat_center,
lon_center=:lon_center,
bio_hectare=:bio_hectare,
bio_biotope_id=:bio_biotope_id,
bio_greenery_id=:bio_greenery_id,
bio_greenery_cover_id=:bio_greenery_cover_id,
bio_temperature=:bio_temperature,
bio_wind=:bio_wind,
locust_have=:locust_have,
locust_type_id=:locust_type_id,
locust_populated=:locust_populated,
eggs_capsules_area=:eggs_capsules_area,
eggs_capsules_density=:eggs_capsules_density,
eggs_capsules_density_to=:eggs_capsules_density_to,
eggs_capsules=:eggs_capsules,
eggs_live=:eggs_live,
eggs_enemies_id=:eggs_enemies_id,
larva_born_id=:larva_born_id,
larva_age_id=:larva_age_id,
larva_painting_id=:larva_painting_id,
larva_behavior_id=:larva_behavior_id,
larva_density=:larva_density,
larva_density_to=:larva_density_to,
kuliguli_age_id=:kuliguli_age_id,
kuliguli_density=:kuliguli_density,
kuliguli_density_to=:kuliguli_density_to,
kuliguli_size=:kuliguli_size,
kuliguli_count=:kuliguli_count,
kuliguli_action_id=:kuliguli_action_id,
imago_wing_id=:imago_wing_id,
imago_maturity=:imago_maturity,
imago_phase_id=:imago_phase_id,
imago_action_id=:imago_action_id,
imago_density=:imago_density,
imago_density_ga=:imago_density_ga,
imago_feeding=:imago_feeding,
imago_copulation=:imago_copulation,
imago_laying=:imago_laying,
imago_flying=:imago_flying,
swarm_maturity=:swarm_maturity,
swarm_density_id=:swarm_density_id,
swarm_density_uid=main.strtouuid(:swarm_density_uid),
swarm_size=:swarm_size,
swarm_count=:swarm_count,
swarm_copulation=:swarm_copulation,
swarm_laying=:swarm_laying,
swarm_flying_direction_id=:swarm_flying_direction_id,
swarm_height_id=:swarm_height_id,
description=:description,
geom=ST_SetSRID(ST_GeomFromGeoJSON(:geom),4326),
test=:test
where uid=main.strtouuid(:uid)
""";
}else{
sql="""
insert into main.frmlocust(
eid,
changed,
company_uid,
user_id,
device_id,
image_name1,
image_name2,
image_name3,
country_id,
region_id,
area,
district,
village,
terrain,
observer,
date,
timezone,
lat_center,
lon_center,
bio_hectare,
bio_biotope_id,
bio_greenery_id,
bio_greenery_cover_id,
bio_temperature,
bio_wind,
locust_have,
locust_type_id,
locust_populated,
eggs_capsules_area,
eggs_capsules_density,
eggs_capsules_density_to,
eggs_capsules,
eggs_live,
eggs_enemies_id,
larva_born_id,
larva_age_id,
larva_painting_id,
larva_behavior_id,
larva_density,
larva_density_to,
kuliguli_age_id,
kuliguli_density,
kuliguli_density_to,
kuliguli_size,
kuliguli_count,
kuliguli_action_id,
imago_wing_id,
imago_maturity,
imago_phase_id,
imago_action_id,
imago_density,
imago_density_ga,
imago_feeding,
imago_copulation,
imago_laying,
imago_flying,
swarm_maturity,
swarm_density_id,
swarm_density_uid,
swarm_size,
swarm_count,
swarm_copulation,
swarm_laying,
swarm_flying_direction_id,
swarm_height_id,
description,
geom,
test,
uid
)values(
:eid,
false,
CAST(:company_uid AS uuid),
:user_id,
:device_id,
:image_name1,
:image_name2,
:image_name3,
:country_id,
:region_id,
:area,
:district,
:village,
:terrain,
:observer,
:date,
CAST(:timezone AS interval),
:lat_center,
:lon_center,
:bio_hectare,
:bio_biotope_id,
:bio_greenery_id,
:bio_greenery_cover_id,
:bio_temperature,
:bio_wind,
:locust_have,
:locust_type_id,
:locust_populated,
:eggs_capsules_area,
:eggs_capsules_density,
:eggs_capsules_density_to,
:eggs_capsules,
:eggs_live,
:eggs_enemies_id,
:larva_born_id,
:larva_age_id,
:larva_painting_id,
:larva_behavior_id,
:larva_density,
:larva_density_to,
:kuliguli_age_id,
:kuliguli_density,
:kuliguli_density_to,
:kuliguli_size,
:kuliguli_count,
:kuliguli_action_id,
:imago_wing_id,
:imago_maturity,
:imago_phase_id,
:imago_action_id,
:imago_density,
:imago_density_ga,
:imago_feeding,
:imago_copulation,
:imago_laying,
:imago_flying,
:swarm_maturity,
:swarm_density_id,
main.strtouuid(:swarm_density_uid),
:swarm_size,
:swarm_count,
:swarm_copulation,
:swarm_laying,
:swarm_flying_direction_id,
:swarm_height_id,
:description,
ST_SetSRID(ST_GeomFromGeoJSON(:geom),4326),
:test,
COALESCE(main.strtouuid(:uid),gen_random_uuid())
)
""";
}
parameters = new MapSqlParameterSource();
parameters.addValue("uid", locust.uid, Types.VARCHAR);
if(locust.eid==null) parameters.addValue("eid", null, Types.INTEGER); else parameters.addValue("eid", Integer.parseInt(locust.eid), Types.INTEGER);
parameters.addValue("company_uid", locust.company_uid, Types.VARCHAR);
if(locust.user_id == null) { parameters.addValue("user_id", null, Types.BIGINT); } else { parameters.addValue("user_id", Long.parseLong(locust.user_id), Types.BIGINT); }
parameters.addValue("device_id", locust.device_id, Types.VARCHAR);
parameters.addValue("image_name1", locust.image_name1, Types.VARCHAR);
parameters.addValue("image_name2", locust.image_name2, Types.VARCHAR);
parameters.addValue("image_name3", locust.image_name3, Types.VARCHAR);
if(locust.country_id == null) { parameters.addValue("country_id", null, Types.BIGINT); } else { parameters.addValue("country_id", Long.parseLong(locust.country_id), Types.BIGINT); }
if(locust.region_id == null) { parameters.addValue("region_id", null, Types.BIGINT); } else { parameters.addValue("region_id", Long.parseLong(locust.region_id), Types.BIGINT); }
parameters.addValue("area", locust.area, Types.VARCHAR);
parameters.addValue("district", locust.district, Types.VARCHAR);
parameters.addValue("village", locust.village, Types.VARCHAR);
parameters.addValue("terrain", locust.terrain, Types.VARCHAR);
parameters.addValue("observer", locust.observer, Types.VARCHAR);
if(locust.date==null)
{
parameters.addValue("date", null, Types.DATE);
}else
{
parameters.addValue("date", locust.date, Types.TIMESTAMP);
}
parameters.addValue("timezone", locust.timezone, Types.VARCHAR);
if(locust.lat_center==null) parameters.addValue("lat_center", null, Types.DOUBLE); else parameters.addValue("lat_center", Double.parseDouble(locust.lat_center), Types.DOUBLE);
if(locust.lon_center==null) parameters.addValue("lon_center", null, Types.DOUBLE); else parameters.addValue("lon_center", Double.parseDouble(locust.lon_center), Types.DOUBLE);
if(locust.bio_hectare==null) parameters.addValue("bio_hectare", null, Types.DOUBLE); else parameters.addValue("bio_hectare",Double.parseDouble(locust.bio_hectare), Types.DOUBLE);
if(locust.bio_biotope_id==null) parameters.addValue("bio_biotope_id", null, Types.BIGINT); else parameters.addValue("bio_biotope_id",Long.parseLong(locust.bio_biotope_id), Types.BIGINT);
if(locust.bio_greenery_id==null) parameters.addValue("bio_greenery_id", null, Types.BIGINT); else parameters.addValue("bio_greenery_id", Long.parseLong(locust.bio_greenery_id), Types.BIGINT);
if(locust.bio_greenery_cover_id==null) parameters.addValue("bio_greenery_cover_id", null, Types.BIGINT); else parameters.addValue("bio_greenery_cover_id",Long.parseLong(locust.bio_greenery_cover_id), Types.BIGINT);
if(locust.bio_temperature==null) parameters.addValue("bio_temperature", null, Types.DOUBLE); else parameters.addValue("bio_temperature",Double.parseDouble(locust.bio_temperature), Types.DOUBLE);
if(locust.bio_wind==null) parameters.addValue("bio_wind", null, Types.DOUBLE); else parameters.addValue("bio_wind",Double.parseDouble(locust.bio_wind), Types.DOUBLE);
if(locust.locust_have==null) parameters.addValue("locust_have", null, Types.BIGINT); else parameters.addValue("locust_have",Long.parseLong(locust.locust_have), Types.BIGINT);
if(locust.locust_type_id==null) parameters.addValue("locust_type_id", null, Types.BIGINT); else parameters.addValue("locust_type_id",Long.parseLong(locust.locust_type_id), Types.BIGINT);
if(locust.locust_populated==null) parameters.addValue("locust_populated", null, Types.DOUBLE); else parameters.addValue("locust_populated",Double.parseDouble(locust.locust_populated), Types.DOUBLE);
if(locust.eggs_capsules_area==null) parameters.addValue("eggs_capsules_area", null, Types.DOUBLE); else parameters.addValue("eggs_capsules_area",Double.parseDouble(locust.eggs_capsules_area), Types.DOUBLE);
if(locust.eggs_capsules_density==null) parameters.addValue("eggs_capsules_density", null, Types.DOUBLE); else parameters.addValue("eggs_capsules_density",Double.parseDouble(locust.eggs_capsules_density), Types.DOUBLE);
if(locust.eggs_capsules_density_to==null) parameters.addValue("eggs_capsules_density_to", null, Types.DOUBLE); else parameters.addValue("eggs_capsules_density_to",Double.parseDouble(locust.eggs_capsules_density_to), Types.DOUBLE);
if(locust.eggs_capsules==null) parameters.addValue("eggs_capsules", null, Types.DOUBLE); else parameters.addValue("eggs_capsules",Double.parseDouble(locust.eggs_capsules), Types.DOUBLE);
if(locust.eggs_live==null) parameters.addValue("eggs_live", null, Types.DOUBLE); else parameters.addValue("eggs_live",Double.parseDouble(locust.eggs_live), Types.DOUBLE);
if(locust.eggs_enemies_id==null) parameters.addValue("eggs_enemies_id", null, Types.BIGINT); else parameters.addValue("eggs_enemies_id",Long.parseLong(locust.eggs_enemies_id), Types.BIGINT);
if(locust.larva_born_id==null) parameters.addValue("larva_born_id", null, Types.BIGINT); else parameters.addValue("larva_born_id",Long.parseLong(locust.larva_born_id), Types.BIGINT);
if(locust.larva_age_id==null) parameters.addValue("larva_age_id", null, Types.BIGINT); else parameters.addValue("larva_age_id",Long.parseLong(locust.larva_age_id), Types.BIGINT);
if(locust.larva_painting_id==null) parameters.addValue("larva_painting_id", null, Types.BIGINT); else parameters.addValue("larva_painting_id",Long.parseLong(locust.larva_painting_id), Types.BIGINT);
if(locust.larva_behavior_id==null) parameters.addValue("larva_behavior_id", null, Types.BIGINT); else parameters.addValue("larva_behavior_id",Long.parseLong(locust.larva_behavior_id), Types.BIGINT);
if(locust.larva_density==null) parameters.addValue("larva_density", null, Types.DOUBLE); else parameters.addValue("larva_density",Double.parseDouble(locust.larva_density), Types.DOUBLE);
if(locust.larva_density_to==null) parameters.addValue("larva_density_to", null, Types.DOUBLE); else parameters.addValue("larva_density_to",Double.parseDouble(locust.larva_density_to), Types.DOUBLE);
if(locust.kuliguli_age_id==null) parameters.addValue("kuliguli_age_id", null, Types.BIGINT); else parameters.addValue("kuliguli_age_id",Long.parseLong(locust.kuliguli_age_id), Types.BIGINT);
if(locust.kuliguli_density==null) parameters.addValue("kuliguli_density", null, Types.DOUBLE); else parameters.addValue("kuliguli_density",Double.parseDouble(locust.kuliguli_density), Types.DOUBLE);
if(locust.kuliguli_density_to==null) parameters.addValue("kuliguli_density_to", null, Types.DOUBLE); else parameters.addValue("kuliguli_density_to",Double.parseDouble(locust.kuliguli_density_to), Types.DOUBLE);
if(locust.kuliguli_size==null) parameters.addValue("kuliguli_size", null, Types.DOUBLE); else parameters.addValue("kuliguli_size",Double.parseDouble(locust.kuliguli_size), Types.DOUBLE);
if(locust.kuliguli_count==null) parameters.addValue("kuliguli_count", null, Types.DOUBLE); else parameters.addValue("kuliguli_count",Double.parseDouble(locust.kuliguli_count), Types.DOUBLE);
if(locust.kuliguli_action_id==null) parameters.addValue("kuliguli_action_id", null, Types.BIGINT); else parameters.addValue("kuliguli_action_id",Long.parseLong(locust.kuliguli_action_id), Types.BIGINT);
if(locust.imago_wing_id==null) parameters.addValue("imago_wing_id", null, Types.BIGINT); else parameters.addValue("imago_wing_id",Long.parseLong(locust.imago_wing_id), Types.BIGINT);
if(locust.imago_maturity==null) parameters.addValue("imago_maturity", null, Types.BOOLEAN);
else {
if(locust.imago_maturity.equals("1")) parameters.addValue("imago_maturity",true,Types.BOOLEAN);
else parameters.addValue("imago_maturity",false,Types.BOOLEAN);
}
if(locust.imago_phase_id==null) parameters.addValue("imago_phase_id", null, Types.BIGINT); else parameters.addValue("imago_phase_id",Long.parseLong(locust.imago_phase_id), Types.BIGINT);
if(locust.imago_action_id==null) parameters.addValue("imago_action_id", null, Types.BIGINT); else parameters.addValue("imago_action_id",Long.parseLong(locust.imago_action_id), Types.BIGINT);
if(locust.imago_density==null) parameters.addValue("imago_density", null, Types.DOUBLE); else parameters.addValue("imago_density",Double.parseDouble(locust.imago_density), Types.DOUBLE);
if(locust.imago_density_ga==null) parameters.addValue("imago_density_ga", null, Types.DOUBLE); else parameters.addValue("imago_density_ga",Double.parseDouble(locust.imago_density_ga), Types.DOUBLE);
if(locust.imago_feeding==null) parameters.addValue("imago_feeding", null, Types.BOOLEAN);
else {
if(locust.imago_feeding.equals("1")) parameters.addValue("imago_feeding",true,Types.BOOLEAN);
else parameters.addValue("imago_feeding",false,Types.BOOLEAN);
}
if(locust.imago_copulation==null) parameters.addValue("imago_copulation", null, Types.BOOLEAN);
else {
if(locust.imago_copulation.equals("1")) parameters.addValue("imago_copulation",true,Types.BOOLEAN);
else parameters.addValue("imago_copulation",false,Types.BOOLEAN);
}
if(locust.imago_laying==null) parameters.addValue("imago_laying", null, Types.BOOLEAN);
else {
if(locust.imago_laying.equals("1")) parameters.addValue("imago_laying",true,Types.BOOLEAN);
else parameters.addValue("imago_laying",false,Types.BOOLEAN);
}
if(locust.imago_flying==null) parameters.addValue("imago_flying", null, Types.BOOLEAN);
else {
if(locust.imago_flying.equals("1")) parameters.addValue("imago_flying",true,Types.BOOLEAN);
else parameters.addValue("imago_flying",false,Types.BOOLEAN);
}
if(locust.swarm_maturity==null) parameters.addValue("swarm_maturity", null, Types.BOOLEAN);
else {
if(locust.swarm_maturity.equals("1")) parameters.addValue("swarm_maturity",true,Types.BOOLEAN);
else parameters.addValue("swarm_maturity",false,Types.BOOLEAN);
}
if(locust.swarm_density_id==null) parameters.addValue("swarm_density_id", null, Types.BIGINT); else parameters.addValue("swarm_density_id",Long.parseLong(locust.swarm_density_id), Types.BIGINT);
if(locust.swarm_density_uid==null) parameters.addValue("swarm_density_uid", null, Types.VARCHAR); else parameters.addValue("swarm_density_uid",locust.swarm_density_uid, Types.VARCHAR);
if(locust.swarm_size==null) parameters.addValue("swarm_size", null, Types.DOUBLE); else parameters.addValue("swarm_size",Double.parseDouble(locust.swarm_size), Types.DOUBLE);
if(locust.swarm_count==null) parameters.addValue("swarm_count", null, Types.DOUBLE); else parameters.addValue("swarm_count",Double.parseDouble(locust.swarm_count), Types.DOUBLE);
if(locust.swarm_copulation==null) parameters.addValue("swarm_copulation", null, Types.BOOLEAN);
else {
if(locust.swarm_copulation.equals("1")) parameters.addValue("swarm_copulation",true,Types.DOUBLE);
else parameters.addValue("swarm_copulation",false,Types.DOUBLE);
}
if(locust.swarm_laying==null) parameters.addValue("swarm_laying", null, Types.BOOLEAN);
else {
if(locust.swarm_laying.equals("1")) parameters.addValue("swarm_laying",true,Types.DOUBLE);
else parameters.addValue("swarm_laying",false,Types.DOUBLE);
}
if(locust.swarm_flying_direction_id==null) parameters.addValue("swarm_flying_direction_id", null, Types.BIGINT); else parameters.addValue("swarm_flying_direction_id",Long.parseLong(locust.swarm_flying_direction_id), Types.BIGINT);
if(locust.swarm_height_id==null) parameters.addValue("swarm_height_id", null, Types.BIGINT); else parameters.addValue("swarm_height_id",Long.parseLong(locust.swarm_height_id), Types.BIGINT);
parameters.addValue("description", locust.description, Types.VARCHAR);
parameters.addValue("geom", locust.geom, Types.VARCHAR);
if(locust.test==null) parameters.addValue("test", null, Types.BOOLEAN);
else {
if(locust.test.equals("1")) parameters.addValue("test",true, Types.BOOLEAN);
else parameters.addValue("test",false,Types.BOOLEAN);
}
try {
int rowsAffected = jdbcTemplate.update(sql, parameters);
return rowsAffected > 0;
} catch (Exception ex) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), ex.getMessage(), ex);
return false;
}
}
}

View File

@ -0,0 +1,119 @@
package org.ccalm.main.api;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.servlet.ServletContext;
import org.ccalm.main.models.ErrorResponseModel;
import org.gdal.gdal.Band;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconstConstants;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.ServletContextAware;
import tools.Translation;
//import tools.Translation;
import java.util.*;
@Controller
public class APICountries implements ServletContextAware {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(APICountries.class);
private ServletContext context;
private final NamedParameterJdbcTemplate jdbcTemplate;
private final Environment environment;
private HikariDataSource dataSource;
@Override
public void setServletContext(ServletContext servletContext) {
this.context=servletContext;
}
@Autowired
public APICountries(NamedParameterJdbcTemplate jdbcTemplate, HikariDataSource dataSource, Environment environment) {
this.jdbcTemplate = jdbcTemplate;
this.environment = environment;
this.dataSource = dataSource;
}
@RequestMapping(value = {"/api/locust/v01/download-countries"}, method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<Map<String, Object>> downloadCountries() {
String apiUrl = "https://api.worldbank.org/v2/country?format=json&per_page=600";
List<Map<String, Object>> countriesList = new ArrayList<>();
try {
// 1. Запрос данных с API
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity(apiUrl, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
// 2. Разбираем JSON
JSONArray jsonArray = new JSONArray(response.getBody());
JSONArray countries = jsonArray.getJSONArray(1);
for (int i = 0; i < countries.length(); i++) {
JSONObject country = countries.getJSONObject(i);
String code3 = country.optString("id", null); // Код страны (ISO3)
String name = country.optString("name", "Unknown Country");
if (code3 != null && !countryExists(code3)) {
// 3. Добавляем страну в БД
insertCountry(code3, name);
Map<String, Object> countryMap = new HashMap<>();
countryMap.put("code3", code3);
countryMap.put("name", name);
countriesList.add(countryMap);
}
}
}
} catch (Exception e) {
logger.error("Ошибка при загрузке стран: ", e);
}
return countriesList;
}
// Проверка наличия страны в базе
private boolean countryExists(String code3) {
String sql = "SELECT COUNT(*) FROM main.countries WHERE code3 = :code3";
Map<String, Object> params = Collections.singletonMap("code3", code3);
Integer count = jdbcTemplate.queryForObject(sql, params, Integer.class);
return count != null && count > 0;
}
// Вставка новой страны
private void insertCountry(String code3, String name) {
String sql = """
INSERT INTO main.countries (name, code3)
VALUES (:name, :code3)
""";
Map<String, Object> params = Map.of("name", name, "code3", code3);
jdbcTemplate.update(sql, params);
}
@RequestMapping(value = {"/api/locust/v01/get-countries"},method = {RequestMethod.GET},produces = "application/json;charset=utf-8")
public ResponseEntity<Object> getCountries(@CookieValue(value = "lng",defaultValue="1") String language_id) {
Translation trt = new Translation(language_id,jdbcTemplate);
try {
String sql = "SELECT id, name, code3 FROM main.countries where del=false and visible=true ORDER BY name";
List<Map<String, Object>> countries = jdbcTemplate.queryForList(sql,Collections.emptyMap());
return ResponseEntity.ok(countries);
} catch (Exception e) {
String uuid = UUID.randomUUID().toString();
logger.error(uuid, e);
return new ResponseEntity<>(new ErrorResponseModel(200, 10500, trt.trt(false,"Internal_Server_Error"), null, uuid), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -5,10 +5,7 @@ import java.security.KeyFactory;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;
import java.sql.*; import java.sql.*;
import java.util.Base64; import java.util.*;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import jakarta.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpServletResponse;
@ -23,6 +20,7 @@ import org.ccalm.main.TranslationUtils;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
@ -49,7 +47,7 @@ import tools.User;
@Controller @Controller
public class EngineController implements ServletContextAware { public class EngineController implements ServletContextAware {
private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(EngineController.class); private static final org.slf4j.Logger logger = LoggerFactory.getLogger(EngineController.class);
private ServletContext context; private ServletContext context;
private Properties m_props=null; private Properties m_props=null;
//private String m_props_loc=""; //private String m_props_loc="";
@ -73,7 +71,8 @@ public class EngineController implements ServletContextAware {
PublicKey key = keyFactory.generatePublic(spec); PublicKey key = keyFactory.generatePublic(spec);
return key; return key;
} catch (Exception e) { } catch (Exception e) {
logger.error(e); String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e);
} }
return null; return null;
} }
@ -81,7 +80,7 @@ public class EngineController implements ServletContextAware {
/** /**
* Simply selects the home view to render by returning its name. * Simply selects the home view to render by returning its name.
*/ */
@RequestMapping(value = "/engine", method = RequestMethod.GET) @RequestMapping(value = {"/engine", "/api/locust/v01/"}, method = RequestMethod.GET)
public String home( public String home(
Model model, Model model,
HttpServletResponse response, HttpServletResponse response,
@ -89,10 +88,11 @@ public class EngineController implements ServletContextAware {
@CookieValue(value = "lng", defaultValue = "1") int language_id @CookieValue(value = "lng", defaultValue = "1") int language_id
) { ) {
if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) { if (jwt_a.equals("") || Tools.countOccurrences(jwt_a, '.') != 2) {
String redirectUrl = "/login/login?msg=Please_log_in"; String redirectUrl = "/login/?msg=Please_log_in";
model.addAttribute("url", redirectUrl); model.addAttribute("url", redirectUrl);
return "redirect"; return "redirect";
} }
//Проверяю подпись токена //Проверяю подпись токена
Jws<Claims> claims = null; Jws<Claims> claims = null;
PublicKey key_a = getPublicKey(); //SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(env.getProperty("access.key")), "HmacSHA256"); PublicKey key_a = getPublicKey(); //SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(env.getProperty("access.key")), "HmacSHA256");
@ -102,11 +102,15 @@ public class EngineController implements ServletContextAware {
.build() .build()
.parseClaimsJws(jwt_a); .parseClaimsJws(jwt_a);
} catch (Exception e) { } catch (Exception e) {
String redirectUrl = "/login/login?msg=Please_log_in"; String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage());
String redirectUrl = "/login/?msg=Please_log_in";
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
model.addAttribute("url", redirectUrl); model.addAttribute("url", redirectUrl);
return "redirect"; return "redirect";
} }
//logger.warn("page engine is start");
//if(language_id!=null && !language_id.isEmpty()) user.language_id=language_id; //if(language_id!=null && !language_id.isEmpty()) user.language_id=language_id;
//logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id); //logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id);
@ -125,7 +129,7 @@ public class EngineController implements ServletContextAware {
} }
} catch( DataAccessException ex ) } catch( DataAccessException ex )
{ {
logger.info(ex.getMessage()); logger.error(ex.getMessage());
} }
//Send user name and role //Send user name and role
@ -174,6 +178,7 @@ public class EngineController implements ServletContextAware {
Document doc = null; Document doc = null;
try { try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(isXML); doc = dBuilder.parse(isXML);
} catch (Exception ex) { } catch (Exception ex) {

View File

@ -5,8 +5,12 @@ import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import jakarta.servlet.ServletContext; import jakarta.servlet.ServletContext;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.ccalm.main.AcceptJSON;
import org.ccalm.main.engine.EngineController; import org.ccalm.main.engine.EngineController;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
@ -29,7 +33,7 @@ import java.util.UUID;
@Controller @Controller
public class LoginController implements ServletContextAware { public class LoginController implements ServletContextAware {
private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(EngineController.class); private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
private javax.servlet.ServletContext context; private javax.servlet.ServletContext context;
private final NamedParameterJdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate jdbcTemplate;
@ -63,7 +67,7 @@ public class LoginController implements ServletContextAware {
} }
} catch (Exception ex) { } catch (Exception ex) {
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
logger.error(uuid, ex); logger.error(MarkerFactory.getMarker(uuid), ex.getMessage(), ex);
} }
return "login/login"; return "login/login";

View File

@ -0,0 +1,107 @@
package org.ccalm.main.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Collections;
import java.util.List;
@Schema(
description = "Error API response",
example = "{ \"error_code\": 10000, \"error_message\": [\"Internal_Server_Error\",\"Please_log_in\"], \"error_setting\": [\"99;day\",\"1;2\"], \"error_marker\": \"2a449883-c7c6-468e-b3ae-5f73fc96627d\" }"
)
public class ErrorResponseModel {
@JsonIgnore
private int httpCode;
@Schema(description = "Error code", example = "10000")
@JsonProperty("error_code")
private int errorCode;
@Schema(description = "List of error descriptions", example = "[\"Internal_Server_Error\",\"Please_log_in\"]")
@JsonProperty("error_message")
private List<String> errorMessage;
@Schema(description = "Options for translated text", example = "[\"99;day\",\"1;2\"]")
@JsonProperty("error_setting")
private List<String> errorSetting;
@Schema(description = "Unique identifier for searching in the database", example = "4260aad8-f7ee-4be4-b52c-15d56ec83232")
@JsonProperty("error_marker")
private String errorMarker;
public ErrorResponseModel(int httpCode, int errorCode) {
this.errorCode = errorCode;
this.errorMessage = null;
this.errorSetting = null;
this.errorMarker = null;
}
public ErrorResponseModel(int httpCode, int errorCode, List<String> errorMessage, String errorMarker) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.errorMarker = errorMarker;
}
public ErrorResponseModel(int httpCode, int errorCode, String errorMessage, String errorMarker) {
this.errorCode = errorCode;
this.errorMessage = Collections.singletonList(errorMessage);
this.errorMarker = errorMarker;
}
public ErrorResponseModel(int httpCode, int errorCode, String errorMessage, String errorSetting, String errorMarker) {
this.errorCode = errorCode;
this.errorMessage = Collections.singletonList(errorMessage);
this.errorSetting = Collections.singletonList(errorSetting);
this.errorMarker = errorMarker;
}
public ErrorResponseModel(int httpCode, int errorCode, List<String> errorMessage, List<String> errorSetting, String errorMarker) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.errorSetting = errorSetting;
this.errorMarker = errorMarker;
}
public int getHttp_code() {
return httpCode;
}
public void setHttp_code(int errorCode) {
this.httpCode = httpCode;
}
public int getError_code() {
return errorCode;
}
public void setError_code(int errorCode) {
this.errorCode = errorCode;
}
public List<String> getError_message() {
return errorMessage;
}
public void setError_message(List<String> errorMessage) {
this.errorMessage = errorMessage;
}
public void setError_setting(List<String> errorSetting) {
this.errorSetting = errorSetting;
}
public List<String> getError_setting() {
return errorSetting;
}
public void setError_marker(String errorMarker) {
this.errorMarker = errorMarker;
}
public String getError_marker() {
return errorMarker;
}
}

View File

@ -0,0 +1,219 @@
package org.ccalm.main.models;
import lombok.Getter;
import lombok.Setter;
//import org.ccalm.main.utils.CustomException;
import java.sql.Types;
public class FrmLocustModel {
public String uid;
public String eid; //Внешний идентификатор
public long seq;
public String country_id;
public String country_uid;
public String user_id;
public String phytoType; //Вредители либо обработка
public String observer;
public String device_id = null;
public String image_name1 = null;
public String image_name2 = null;
public String image_name3 = null;
public String lon_center;
public String lat_center;
//Область
public String region_id; //Область
public String region_uid; //Область
public String area; //Rayon
public String district; //Район
public String district_id; //
public String terrain=""; //Название месности
public String village; //Хозяйство или местность
public String locust; //Вид саранчи
//public String locust_id; //Вид саранчи
public String locust_type_id; //Locust species (Вид саранчи)
public String locust_type_uid; //Locust species (Вид саранчи)
public String locust_populated; //Area infested (ha)
public String bio_hectare=null; //Обследованная площадь
public String bio_biotope_id=null; //Тип биотопа
public String bio_biotope_uid=null; //Тип биотопа
public String bio_temperature; //air temperature
public String bio_wind; //Ветер (м/с)
public String bio_greenery_id; //растительность
public String bio_greenery_uid; //растительность
public String bio_greenery_cover_id; //Густота растительного покрова
public String bio_greenery_cover_uid; //Густота растительного покрова
public String phase=null; //Фаза саранчи
public String locust_have; //id Фазы саранчи
public String evp; //ЭФП
public String drawPolygon="null"; //Область обследования GeoGSON
public String size; //Заселённая площадь (polygonArea Площадь контура зоны распространения, в случае если специалист указал его)
//public String date; //Дата
public java.sql.Timestamp date; //Дата
public String timezone;
public String description="";
public String geom;
//Eggs
public String eggs = null; // For CheckBox
public String eggs_capsules_area = null; //Egg-bed (surface in ha)
public String eggs_capsules_density = null; //Плотность яиц
public String eggs_capsules_density_to = null; //Egg-pods (density) to
public String eggs_capsules = null; //Eggs (average)
public String eggs_live = null; //Eggs (viable)
public String eggs_enemies_id = null; //Natural enemies present
public String eggs_enemies_uid = null; //Natural enemies present
//public String eggs_enemies = null; //not using TODO delete field from database
//Hopper (личинки разряженные)
public String larva = null;
public String larva_born = null; //Hatching character varying(255) COLLATE pg_catalog."default" DEFAULT NULL::character varying,
public String larva_born_id = null; // integer,
public String larva_born_uid = null;
public String larva_age_id = null; //Hopper stages integer,
public String larva_age_uid = null; //Hopper stages integer,
public String larva_painting_id = null; //Appearance integer,
public String larva_behavior = null; //Behaviour character varying(50) COLLATE pg_catalog."default" DEFAULT NULL::character varying,
public String larva_behavior_id = null; // integer,
public String larva_behavior_uid = null; // integer,
public String larva_density = null; //Hopper density numeric, (Плотность личинок)
public String larva_density_to = null; //Hopper density to numeric,
//Bands (кулиги)
public String kuliguli = null; // For CheckBox
public String kuliguli_density=null; //Плотность кулиг на м²
public String kuliguli_density_to = null; //плотность максимальная в кулиге
public String kuliguli_size = null; // Размер кулиг
public String kuliguli_count = null; // Количество кулиг
public String kuliguli_action_id = null; // Поведение
public String kuliguli_action_uid = null; // Поведение
public String kuliguli_age_id = null; // Возраст личинок
public String kuliguli_age_uid = null; // Возраст личинок
//Adults (Имаго)
public String imago = null; // For CheckBox
public String imago_wing_id = null;
public String imago_wing_uid = null;
public String imago_maturity = null;
//public String imago_phase = null; not using
public String imago_phase_id = null;
public String imago_phase_uid = null;
public String imago_action = null;
public String imago_action_id = null;
public String imago_action_uid = null;
public String imago_density = null; //Плотность имаго (/м²)*
public String imago_density_ga = null;
public String imago_feeding = null;
public String imago_copulation = null;
public String imago_laying = null; //Кладка яиц
public String imago_flying = null;
public String swarms = null; // For CheckBox
public String swarm_maturity = null; //Maturity boolean,
public String swarm_density_id = null; //Density of swarm integer,
public String swarm_density_uid = null; //Density of swarm integer,
public String swarm_size = null; //Swarm size double precision,
public String swarm_count = null; //Number of swarms double precision,
public String swarm_copulation = null; //Not used boolean,
public String swarm_laying = null; //Not used boolean,
public String swarm_flying_direction_id = null; //Flying direction integer,
public String swarm_height_id = null; //Flying height integer,
public String swarm_height_uid = null; //Flying height integer,
public String company_uid=null;
//Ниже то что относиться только к обработке
public String insecticide_name=null;
public String insecticide_active_substance=null;
public String insecticide_dose=null;
public String spray_platform=null;
public String test=null;
public void update(){
if(
larva_born != null ||
larva_born_id != null ||
larva_born_uid != null ||
larva_age_id != null ||
larva_age_uid != null ||
larva_painting_id != null ||
larva_behavior != null ||
larva_behavior_id != null ||
larva_behavior_uid != null ||
larva_density != null ||
larva_density_to != null
) larva = "true";
if(
eggs_capsules_area != null ||
eggs_capsules_density != null ||
eggs_capsules_density_to != null ||
eggs_capsules != null ||
eggs_live != null ||
eggs_enemies_id != null ||
eggs_enemies_uid != null
) eggs = "true";
//Bands (кулиги)
if(
kuliguli_density != null ||
kuliguli_density_to != null ||
kuliguli_size != null ||
kuliguli_count != null ||
kuliguli_action_id != null ||
kuliguli_action_uid != null ||
kuliguli_age_id != null ||
kuliguli_age_uid != null
) kuliguli = "true";
//Adults (Имаго)
if(
imago_wing_id != null ||
imago_wing_uid != null ||
imago_maturity != null ||
imago_phase_id != null ||
imago_phase_uid != null ||
imago_action != null ||
imago_action_id != null ||
imago_action_uid != null ||
imago_density != null ||
imago_density_ga != null ||
imago_feeding != null ||
imago_copulation != null ||
imago_laying != null ||
imago_flying != null
) imago = "true";
if(
swarm_maturity!=null ||
swarm_density_id!=null ||
swarm_size!=null ||
swarm_count!=null ||
swarm_copulation!=null ||
swarm_laying!=null ||
swarm_flying_direction_id!=null ||
swarm_height_id!=null ||
swarm_height_uid!=null
) swarms = "true";
}
}

View File

@ -0,0 +1,84 @@
package org.ccalm.main.utils;
import lombok.Getter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ccalm.main.models.ErrorResponseModel;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.List;
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class CustomException extends Exception {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CustomException.class);
private ErrorResponseModel error;
@Getter
private boolean saveToLog = false;
public CustomException(int httpCode, int errorCode, String errorMessage, String marker, boolean saveToLog) {
super(errorMessage);
error = new ErrorResponseModel(httpCode, errorCode, errorMessage, marker);
this.saveToLog = saveToLog;
}
public CustomException(int httpCode, int errorCode, String errorMessage, String errorSetting, String marker, boolean saveToLog) {
super(errorMessage);
error = new ErrorResponseModel(httpCode, errorCode, errorMessage, errorSetting, marker);
this.saveToLog = saveToLog;
}
public CustomException(int httpCode, int errorCode, List<String> errorMessages, String marker, boolean saveToLog) {
super(String.join(" ", errorMessages));
error = new ErrorResponseModel(httpCode, errorCode, errorMessages, marker);
this.saveToLog = saveToLog;
}
public CustomException(int httpCode, int errorCode, List<String> errorMessages, List<String> errorSettings, String marker, boolean saveToLog) {
super(String.join(" ", errorMessages));
error = new ErrorResponseModel(httpCode, errorCode, errorMessages, errorSettings, marker);
this.saveToLog = saveToLog;
}
public int getHttpCode() {
return error.getHttp_code();
}
public int getErrorCode() {
return error.getError_code();
}
public String getErrorMarker() {
return error.getError_marker();
}
public List<String> getErrorMessages() {
return error.getError_message();
}
public List<String> getErrorSettings() {
return error.getError_setting();
}
public JSONObject getJson() {
JSONObject json = new JSONObject();
try {
json.put("error_code", this.getErrorCode());
json.put("error_message", this.getErrorMessages());
json.put("error_setting", this.getErrorSettings());
json.put("error_marker", this.getErrorMarker());
} catch (JSONException ex) {
logger.error(ex.getMessage(), ex);
}
return json;
}
public ErrorResponseModel getErrorResponseModel() {
return error;
}
}

View File

@ -0,0 +1,172 @@
package org.ccalm.main.utils;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ccalm.main.engine.EngineController;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Arrays;
import java.util.Base64;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LTools {
//---------------------------------------------------------------------------
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(LTools.class);
//---------------------------------------------------------------------------
public static JSONObject createJSONError(int code, String message, String setting, String marker) {
JSONObject json = new JSONObject();
try {
json.put("error_code", code);
json.put("error_message", Arrays.asList(message));
json.put("error_setting", Arrays.asList(setting));
json.put("error_marker", marker);
} catch (JSONException e) {
String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e);
}
return json;
}
//---------------------------------------------------------------------------
//Зашифровать
public static String encryptText(String pass,String data){
String encryptedBase64="";
String encryptionIV = "jazz_tyt_net_111"; // Ваш вектор инициализации
try {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(pass), "AES");
IvParameterSpec iv = new IvParameterSpec(encryptionIV.getBytes()); // Создание объекта IvParameterSpec для вектора инициализации
cipher.init(Cipher.ENCRYPT_MODE, key, iv); // Инициализация шифра с ключом и вектором инициализации
byte[] encrypted = cipher.doFinal(data.getBytes()); // Шифрование строки
encryptedBase64 = Base64.getEncoder().encodeToString(encrypted); // Преобразование зашифрованных данных в base64
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (BadPaddingException e) {
throw new RuntimeException(e);
}
return encryptedBase64;
}
public static String decryptText(String pass,String data){
String encryptionIV = "jazz_tyt_net_111"; // Ваш вектор инициализации
String decryptedText= "";
try {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(pass), "AES");
IvParameterSpec iv = new IvParameterSpec(encryptionIV.getBytes()); // Создание объекта IvParameterSpec для вектора инициализации
cipher.init(Cipher.DECRYPT_MODE, key, iv); // Инициализация шифра с ключом и вектором инициализации
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data)); // Расшифровка данных
decryptedText = new String(decrypted); // Преобразование расшифрованных данных в строку
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return decryptedText;
}
public static String generateSignature(String pass,String input) {
try {
SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(pass), "HmacSHA256");
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedInput = digest.digest(input.getBytes(StandardCharsets.UTF_8));
byte[] encodedKey = secretKey.getEncoded();
// Создание HMAC-подписи
SecretKeySpec keySpec = new SecretKeySpec(encodedKey, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(keySpec);
byte[] rawHmac = mac.doFinal(encodedInput);
// Кодирование подписи в base64
return Base64.getEncoder().encodeToString(rawHmac);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
return null;
}
}
public static boolean isValidEmail(String email) {
if(email==null || email.isEmpty()) return false;
String EMAIL_REGEX = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
Pattern pattern = Pattern.compile(EMAIL_REGEX);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
public static boolean isInteger(String str) {
if (str == null || str.isEmpty()) {
return false;
}
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
public static String genKey(){
SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
byte[] keyBytes = key.getEncoded();
return Base64.getEncoder().encodeToString(keyBytes);
}
public static String generatePassword(int length) {
String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
SecureRandom random = new SecureRandom();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(CHARACTERS.length());
sb.append(CHARACTERS.charAt(randomIndex));
}
return sb.toString();
}
// Метод для извлечения подписи из JWT токена
public static String extractSignature(String jwtToken) {
String[] jwtParts = jwtToken.split("\\.");
if (jwtParts.length != 3) {
return null;
}
return jwtParts[2];
}
//Для извлечения содержимого токена
public static JSONObject extractToken(String jwtToken) {
String[] jwtParts = jwtToken.split("\\.");
if (jwtParts.length != 3) {
return null;
}
String payloadJson = new String(Base64.getUrlDecoder().decode(jwtParts[1]));
JSONObject payload=null;
try {
payload = new JSONObject(payloadJson);
} catch (JSONException e) {
return null;
}
return payload;
}
}

View File

@ -14,11 +14,6 @@ import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress; import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage;
/**
* A utility class for sending e-mail messages
* @author www.codejava.net
*
*/
public class EmailUtility { public class EmailUtility {
public static void sendEmail(String host, String port, public static void sendEmail(String host, String port,
@ -62,4 +57,5 @@ public class EmailUtility {
// sends the e-mail // sends the e-mail
Transport.send(msg); Transport.send(msg);
} }
} }

View File

@ -194,7 +194,7 @@ public class PreparedStatementNamed {
try{ try{
tm = new java.sql.Timestamp(dfm.parse(value).getTime()); tm = new java.sql.Timestamp(dfm.parse(value).getTime());
} catch (Exception ex) { } catch (Exception ex) {
logger.error("Error",ex.getMessage()); logger.error(ex.getMessage(), ex);
} }
for (int i = 0; i < fields.size(); i++) { for (int i = 0; i < fields.size(); i++) {
if (fields.get(i).name.equals(name)) { if (fields.get(i).name.equals(name)) {

View File

@ -32,7 +32,8 @@ public class Translation {
this.jdbcTemplate = jdbcTemplate; this.jdbcTemplate = jdbcTemplate;
} }
public String trt(String text){ public String trt(boolean translate,String text){
if(translate) {
String sql = """ String sql = """
select select
translation translation
@ -56,5 +57,8 @@ public class Translation {
text = text.replace("_", " "); text = text.replace("_", " ");
} }
return text; return text;
}else {
return text;
}
} }
} }

View File

@ -1,13 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<configuration> <configuration>
<conversionRule conversionWord="exOneLine" converterClass="org.ccalm.main.SingleLineThrowableProxyConverter"/>
<property name="LOGS" value="logs" /> <property name="LOGS" value="logs" />
<springProperty scope="context" name="appName" source="spring.application.name"/> <springProperty scope="context" name="appName" source="spring.application.name"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOGS}/${appName}.log</file> <file>${LOGS}/${appName}.log</file>
<encoder> <encoder class="net.logstash.logback.encoder.LogstashEncoder">
<pattern>{"timestamp":"%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}","thread":"[%thread]","level":"%level","logger":"%logger{36}","message":"%msg"}%n</pattern> <!-- Настраиваем поля для JSON -->
<fieldNames>
<timestamp>timestamp</timestamp>
<thread>thread</thread>
<level>level</level>
<logger>logger</logger>
<message>message</message>
<exception>exception</exception>
</fieldNames>
</encoder> </encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOGS}/${appName}.%d{yyyy-MM-dd}.%i.log</fileNamePattern> <fileNamePattern>${LOGS}/${appName}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
@ -23,7 +33,6 @@
</encoder> </encoder>
</appender> </appender>
<!--root level="info"-->
<root level="warn"> <root level="warn">
<appender-ref ref="FILE" /> <appender-ref ref="FILE" />
<appender-ref ref="CONSOLE" /> <appender-ref ref="CONSOLE" />

View File

@ -17,6 +17,7 @@
<link rel="stylesheet" href="../resources/engine/openlayers/ol.css" type="text/css"> <link rel="stylesheet" href="../resources/engine/openlayers/ol.css" type="text/css">
<!--script src="https://cdn.tailwindcss.com"></script-->
<script type="text/javascript" src="../resources/metadata/jquery.js"></script> <script type="text/javascript" src="../resources/metadata/jquery.js"></script>
<script type="text/javascript" src="../resources/metadata/sprintf.js"></script> <script type="text/javascript" src="../resources/metadata/sprintf.js"></script>
<script type="text/javascript" src="../resources/metadata/qrcode.js"></script> <script type="text/javascript" src="../resources/metadata/qrcode.js"></script>
@ -26,21 +27,21 @@
<!--link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!--link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script--> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script-->
<script type="text/javascript" src="../translation?v=9"></script> <script type="text/javascript" src="/api/translation/v01/array"></script>
<link rel="stylesheet" type="text/css" href="../resources/metadata/dbms/dbms.css?v=14"/> <link rel="stylesheet" type="text/css" href="../resources/metadata/dbms/dbms.css?v=15"/>
<script type="text/javascript" src="../resources/metadata/dbms/BrowserDetect.js?v=14"></script> <script type="text/javascript" src="../resources/metadata/dbms/BrowserDetect.js?v=15"></script>
<script type="text/javascript" src="../resources/metadata/dbms/tools.js?v=14"></script> <script type="text/javascript" src="../resources/metadata/dbms/tools.js?v=15"></script>
<script type="text/javascript" src="../resources/metadata/dbms/window.js?v=14"></script> <script type="text/javascript" src="../resources/metadata/dbms/window.js?v=15"></script>
<script type="text/javascript" src="../resources/metadata/dbms/editrecord.js?v=14"></script> <script type="text/javascript" src="../resources/metadata/dbms/editrecord.js?v=15"></script>
<script type="text/javascript" src="../resources/metadata/dbms/showrecord.js?v=14"></script> <script type="text/javascript" src="../resources/metadata/dbms/showrecord.js?v=15"></script>
<script type="text/javascript" src="../resources/metadata/dbms/tabs.js?v=14"></script> <script type="text/javascript" src="../resources/metadata/dbms/tabs.js?v=15"></script>
<script type="text/javascript" src="../resources/metadata/dbms/login.js?v=14"></script> <script type="text/javascript" src="../resources/metadata/dbms/login.js?v=15"></script>
<script type="text/javascript" src="../resources/metadata/dbms/log.js?v=14"></script> <script type="text/javascript" src="../resources/metadata/dbms/log.js?v=15"></script>
<script type="text/javascript" src="../resources/metadata/tree/tree.js?v=14"></script> <script type="text/javascript" src="../resources/metadata/tree/tree.js?v=15"></script>
<script type="text/javascript" src="../resources/engine/popup.js?v=14"></script> <script type="text/javascript" src="../resources/engine/popup.js?v=15"></script>
<script type="text/javascript" src="../resources/engine/index.js?v=21"></script> <script type="text/javascript" src="../resources/engine/index.js?v=22"></script>
<script type="text/javascript" src="../resources/engine/user.js?v=14"></script> <script type="text/javascript" src="../resources/engine/user.js?v=17"></script>
<style> <style>
html, html,
@ -144,7 +145,7 @@ select{
</style> </style>
<script> <script type="application/javascript">
if(window.location.host.indexOf('locust.kz')>=0){ if(window.location.host.indexOf('locust.kz')>=0){
window.location.href = "https://ccalm.org"; window.location.href = "https://ccalm.org";
@ -354,6 +355,8 @@ function onLoadPage()
} }
</script> </script>
</head> </head>
<body> <body>
@ -373,6 +376,7 @@ function onLoadPage()
<td style="width:80%;padding-left:5px;color: rgb(100, 100, 100);" id="user_name">{{name}} {{patronymic}} {{surname}} (<span>{{ roles.join(', ') }}</span>)</td> <td style="width:80%;padding-left:5px;color: rgb(100, 100, 100);" id="user_name">{{name}} {{patronymic}} {{surname}} (<span>{{ roles.join(', ') }}</span>)</td>
<td style="padding-left:5px;" th:text="${Language}">Language</td> <td style="padding-left:5px;" th:text="${Language}">Language</td>
<td style="padding-left:5px; width:200px;position: relative;"> <td style="padding-left:5px; width:200px;position: relative;">
<!--select id="lang" onchange="setCookie('lng',this.value,365,'/'); location.reload();" style="width: 95%; position: absolute; transform: translate(0%, -52%); z-index: 10000;"-->
<select id="lang" onchange="setCookie('lng',this.value,365,'/'); location.reload();" style="width: 95%; position: absolute; transform: translate(0%, -52%); z-index: 10000;"> <select id="lang" onchange="setCookie('lng',this.value,365,'/'); location.reload();" style="width: 95%; position: absolute; transform: translate(0%, -52%); z-index: 10000;">
<option value="3">English</option> <option value="3">English</option>
<option value="1">Russian Русский</option> <option value="1">Russian Русский</option>
@ -1167,8 +1171,21 @@ new Calendar({
<td style="padding: 1px; width: 158px; white-space: nowrap;" th:text="${Year}">Year</td> <td style="padding: 1px; width: 158px; white-space: nowrap;" th:text="${Year}">Year</td>
<td style="padding: 1px;"> <td style="padding: 1px;">
<select style="width: 100%;" id="filter_ivi_year"> <select style="width: 100%;" id="filter_ivi_year">
<option value="2023_03_05">2023 (03..05)</option>
<option value="2025_02_04">2025 (02..04)</option>
<option value="2025_03_05">2025 (03..05)</option>
<option value="2025_04_06">2025 (04..06)</option>
<option value="2025_05_07">2025 (05..07)</option>
<option value="2024_02_04">2024 (02..04)</option>
<option value="2024_03_05">2024 (03..05)</option>
<option value="2024_04_06">2024 (04..06)</option>
<option value="2024_05_07">2024 (05..07)</option>
<option value="2023_02_04">2023 (02..04)</option> <option value="2023_02_04">2023 (02..04)</option>
<option value="2023_03_05">2023 (03..05)</option>
<option value="2023_04_06">2023 (04..06)</option>
<option value="2023_05_07">2023 (05..07)</option>
<option value="2022_02_04">2022 (02..04)</option> <option value="2022_02_04">2022 (02..04)</option>
<option value="2022_03_05">2022 (03..05)</option> <option value="2022_03_05">2022 (03..05)</option>
@ -1412,8 +1429,6 @@ new Calendar({
<div id="tab_admin" style="position: absolute; width:100px; height:100px; padding:3px; overflow:scroll;"> <div id="tab_admin" style="position: absolute; width:100px; height:100px; padding:3px; overflow:scroll;">
<button id="btnChangePassword" class="main" style="width:100%;margin-top:1px;" onclick="g_user.changePassword();" th:text="${Change_login_password}">Change_login_password</button>
<div id="lblReports" th:text="${Reports}">Reports</div> <div id="lblReports" th:text="${Reports}">Reports</div>
<button class="main" style="width:100%;margin-top:1px;" onclick="showReportCountries();" th:text="${Filling_forms_by_countries}">Filling_forms_by_countries</button> <button class="main" style="width:100%;margin-top:1px;" onclick="showReportCountries();" th:text="${Filling_forms_by_countries}">Filling_forms_by_countries</button>
<button class="main" style="width:100%;margin-top:1px;" onclick="showReportInspectors();" th:text="${Completed_forms_by_tablets}">Completed_forms_by_tablets</button> <button class="main" style="width:100%;margin-top:1px;" onclick="showReportInspectors();" th:text="${Completed_forms_by_tablets}">Completed_forms_by_tablets</button>
@ -1654,6 +1669,9 @@ var vectorSourceV = new ol.source.Vector({});
var vectorSourceDel = new ol.source.Vector({}); var vectorSourceDel = new ol.source.Vector({});
var vectorSourceDelV = new ol.source.Vector({}); var vectorSourceDelV = new ol.source.Vector({});
var vectorSourceHealth = new ol.source.Vector({});
var vectorSourceHealthV = new ol.source.Vector({});
var vectorSourceArea = new ol.source.Vector({}); var vectorSourceArea = new ol.source.Vector({});
var vectorSourceCheckpoint = new ol.source.Vector({}); var vectorSourceCheckpoint = new ol.source.Vector({});
@ -1758,6 +1776,14 @@ map = new ol.Map({
new ol.layer.Vector({ new ol.layer.Vector({
source: vectorSourceDelV, source: vectorSourceDelV,
zIndex: 50 zIndex: 50
}),
new ol.layer.Vector({
source: vectorSourceHealth,
zIndex: 100
}),
new ol.layer.Vector({
source: vectorSourceHealthV,
zIndex: 50
}), }),
new ol.layer.Vector({ new ol.layer.Vector({
source: vectorSourceArea, source: vectorSourceArea,
@ -1884,8 +1910,13 @@ map.on('singleclick', function(evt){ //map.on('click', function(evt){
if(feature.userType=="FrmCheckpoint") if(feature.userType=="FrmCheckpoint")
{ {
let coordinates = feature.getGeometry().getCoordinates(); let coordinates = feature.getGeometry().getCoordinates();
content.innerHTML = '<b>'+trt('Title')+'</b>: '+feature.userTitle+'<br><b>'+trt('Creator')+'</b>: '+feature.userName+'<br><b>'+trt('Radius')+'</b>: '+feature.userRadius+'m.'+'<br><b>'+trt('Want_temperature')+'</b>: '+feature.userTemperature+'°C'; content.innerHTML =
content.innerHTML += '<table><tr><td><button class="main" onclick="g_density_larval.callData('+feature.userID+');">'+trt('Hopper_density')+'</button></td><td><button class="main" onclick="g_density_imago.callData('+feature.userID+');">'+trt('Adult_density')+'</button></td></tr></table>'; '<span style="white-space: nowrap;"><b>' + trt('Title') + '</b>:&nbsp;' + feature.userTitle + '</span><br>' +
'<span style="white-space: nowrap;"><b>' + trt('Creator') + '</b>:&nbsp;' + feature.userName + '</span><br>' +
'<span style="white-space: nowrap;"><b>' + trt('Radius') + '</b>:&nbsp;' + feature.userRadius + 'm.</span><br>' +
'<span style="white-space: nowrap;"><b>' + trt('Want_air_temperature') + '</b>:&nbsp;' + feature.userTemperature_air + '°C</span><br>' +
'<span style="white-space: nowrap;"><b>' + trt('Want_soil_temperature') + '</b>:&nbsp;' + feature.userTemperature_air + '°C</span>';
content.innerHTML += '<table style="width: 100%;border-spacing: 2px; border-collapse: separate;"><tr><td><button class="main" style="width: 100%;" onclick="g_density_larval.callData('+feature.userID+');">'+trt('Hopper_density')+'</button></td><td><button class="main" style="width: 100%;" onclick="g_density_imago.callData('+feature.userID+');">'+trt('Adult_density')+'</button></td></tr></table>';
overlay.setPosition(coordinates); overlay.setPosition(coordinates);
}else{ }else{
overlay.setPosition(undefined); overlay.setPosition(undefined);
@ -1994,7 +2025,6 @@ window.onresize = function()
} }
onresize(); onresize();
onLoadPage(); onLoadPage();
</script> </script>

View File

@ -1,97 +1,382 @@
<html> <!DOCTYPE html>
<html lang="en-GB">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="UTF-8">
<link rel="shortcut icon" href="./resources/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Automated system of data collection</title> <meta name="description" content="Caucasus and Central Asia Locust Management System (CCALM) - A sophisticated system for monitoring and analysing locust populations in the CCA region using GIS and remote sensing.">
<meta name="yandex-verification" content="2cb5374be0668fe9" /> <meta name="keywords" content="CCALM, Locust Management, Caucasus, Central Asia, Agriculture, Pest Control, GIS, Remote Sensing, Environmental Monitoring, FAO">
<meta name="author" content="CCALM">
<script src="../resources/metadata/dbms/tools.js?v=9"></script> <title>Caucasus and Central Asia Locust Management System (CCALM)</title>
<script src="../resources/metadata/dbms/window.js?v=10"></script>
<meta name="description" content="According to the implementation of the Road Map program to improve national and regional locust control in the Caucasus and Central Asia (CCA) developed a system of monitoring and analysis designed to control locusts in the CCA using a geographic information system and remote sensing technology"> <!-- Favicon -->
<link rel="icon" href="https://ccalm.org/resources/images/locust.png" type="image/x-icon">
<style type="text/css"> <!-- Google Fonts -->
html,body <link rel="preconnect" href="https://fonts.googleapis.com">
{ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
height:100%; <link href="https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@0,400..800;1,400..800&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
min-height:100%;
margin:0px; <!-- Phosphor Icons -->
padding:0px; <script src="https://unpkg.com/@phosphor-icons/web"></script>
text-align:center;
background-color: #f0f0f0; <!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* Define custom properties (CSS variables) for a consistent and maintainable theme */
:root {
/* These will be populated by JavaScript from the config object */
} }
.content
{ /* Base body styling */
max-width:960px; body {
height:100%; font-family: var(--font-primary);
min-height:100%; background-color: var(--color-bg-core);
margin:0 auto; color: #374151; /* A neutral, dark grey for text */
text-align:left; scroll-behavior: smooth;
background-color: #ffffff; }
/* Header with a single green background color */
.wave-header {
background: var(--color-wave-3); /* Single green line as requested */
position: relative;
color: var(--color-text-on-wave);
}
/* A more refined SVG wave shape for a sophisticated transition */
.wave-header::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 100px; /* Adjusted wave height */
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1440 320'%3E%3Cpath fill='%23F8F7F2' fill-opacity='1' d='M0,224L1440,128L1440,320L0,320Z'%3E%3C/path%3E%3C/svg%3E");
background-repeat: no-repeat;
background-size: cover;
background-position: bottom;
transform: translateY(1px); /* Prevents rendering gaps */
}
/* Enhanced button styling for a more interactive feel */
.btn-custom {
background-color: var(--color-button);
color: white;
font-weight: 600;
padding: 0.85rem 2.5rem; /* Slightly larger padding */
border-radius: 0.5rem;
transition: all 0.3s ease;
display: inline-block;
text-decoration: none;
box-shadow: 0 4px 14px 0 rgba(0, 0, 0, 0.1);
}
.btn-custom:hover {
background-color: var(--color-button-hover);
transform: translateY(-3px) scale(1.03);
box-shadow: 0 7px 20px 0 rgba(0, 0, 0, 0.15);
}
/* Enhanced card styling with improved shadows and hover effects */
.info-card {
background-color: white;
border: 1px solid #E5E7EB;
border-radius: 0.75rem;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.03), 0 2px 4px -2px rgba(0, 0, 0, 0.03);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.info-card:hover {
transform: translateY(-8px);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.07), 0 4px 6px -4px rgba(0, 0, 0, 0.07);
}
/* Styling for the icon container within the cards */
.icon-container {
width: 80px;
height: 80px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
background-color: #f0fdf4; /* A very light green */
color: var(--color-button);
transition: all 0.3s ease;
}
.info-card:hover .icon-container {
background-color: var(--color-button);
color: white;
transform: scale(1.1);
}
/* Animation classes for scroll-triggered fade-in effects */
.fade-in-section {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.6s ease-out, transform 0.6s ease-out;
}
.fade-in-section.is-visible {
opacity: 1;
transform: translateY(0);
}
/* Language selector styling */
.language-selector {
position: absolute;
top: 20px;
right: 20px;
z-index: 50;
}
.language-button {
background: rgba(255, 255, 255, 0.9);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 0.5rem;
padding: 0.5rem 1rem;
color: #374151;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
gap: 0.5rem;
}
.language-button:hover {
background: rgba(255, 255, 255, 1);
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.language-button.active {
background: var(--color-button);
color: white;
} }
</style> </style>
<script type="text/javascript"> </head>
<body class="antialiased">
function setCookie (name, value, expires, path, domain, secure) <!--
{ Website configuration object.
var exdate=new Date(); All user-facing text, colors, fonts, and URLs are defined here.
exdate.setDate(exdate.getDate() + expires); This makes the site easily editable without touching the HTML structure.
expires=exdate.toUTCString() -->
<script>
const config = {
// Text content
en: {
title: "Caucasus and Central Asia Locust Management System (CCALM)",
introText: `The Automated System for Data Collection (ASDC) and the Geographic Information System (GIS) "Caucasus and Central Asia Locust Management System (CCALM)" were created as part of the "Programme to improve national and regional locust management in Caucasus and Central Asia (CCA)", implemented by the Food and Agriculture Organization (FAO) of the United Nations to the benefit of ten countries. Used on tablets or smartphones, ASDC allows field data collection during locust survey and control and near real-time transmission to the GIS. CCALM, filled with ASDC data and other sources (satellite products), aims at improving analysis, forecasting and reporting at national and regional levels and as such contributes to early warning and early reaction.`,
card1: {
title: "Automated System for Data Collection (ASDC)",
buttonText: "Download ASDC"
},
card2: {
title: "Caucasus and Central Asia Locust Management System (CCALM)",
buttonText: "Access CCALM"
},
footer: {
contactTitle: "Contact Us",
phone: "Tel 8(727)3967038",
email: "info@ccalm.org",
copyrightYear: "2025"
}
},
ru: {
title: "Система управления саранчовыми на Кавказе и в Центральной Азии (CCALM)",
introText: `Автоматизированная система сбора данных (ASDC) и геоинформационная система (ГИС) "Система управления саранчовыми на Кавказе и в Центральной Азии (CCALM)" были созданы в рамках "Программы по улучшению национальной и региональной борьбы с саранчой на Кавказе и в Центральной Азии (КЦА)", реализуемой Продовольственной и сельскохозяйственной организацией Объединенных Наций (ФАО) в интересах десяти стран. Используемая на планшетах или смартфонах, ASDC позволяет собирать полевые данные во время обследования и борьбы с саранчой и передавать их в ГИС практически в режиме реального времени. CCALM, наполненный данными ASDC и других источников (спутниковые продукты), призван улучшить анализ, прогнозирование и отчетность на национальном и региональном уровнях и, таким образом, способствовать раннему предупреждению и раннему реагированию.`,
card1: {
title: "Автоматизированная система сбора данных (ASDC)",
buttonText: "Скачать ASDC"
},
card2: {
title: "Система управления саранчовыми на Кавказе и в Центральной Азии (CCALM)",
buttonText: "Доступ к CCALM"
},
footer: {
contactTitle: "Контакты:",
phone: "Тел.: 8(727)3967038",
email: "info@ccalm.org",
copyrightYear: "2025"
}
},
// URLs for buttons and links
urls: {
asdc: "https://play.google.com/store/apps/details?id=kz.istt.locust",
ccalm: "/engine",
phone: "tel:+77273967038",
email: "mailto:info@ccalm.org"
},
// Style configuration
styles: {
fontPrimary: "'EB Garamond', serif",
colors: {
button: "#16A34A",
buttonHover: "#15803D", // Darker shade for hover
wave1: "#5D7958", // Bottom wave color
wave2: "#6F876E", // Middle wave color
wave3: "#8B9E8D", // Top wave color
textOnWave: "#EEF0EE",
bgCore: "#F8F7F2",
bgFooter: "#1F2937"
}
}
};
document.cookie = name + "=" + escape(value) + // Current language state
((expires) ? "; expires=" + expires : "") + let currentLanguage = 'en';
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") + // This function applies styles from the config object to CSS custom properties (variables)
((secure) ? "; secure" : ""); function applyStyles() {
const root = document.documentElement;
root.style.setProperty('--font-primary', config.styles.fontPrimary);
root.style.setProperty('--color-button', config.styles.colors.button);
root.style.setProperty('--color-button-hover', config.styles.colors.buttonHover);
root.style.setProperty('--color-wave-1', config.styles.colors.wave1);
root.style.setProperty('--color-wave-2', config.styles.colors.wave2);
root.style.setProperty('--color-wave-3', config.styles.colors.wave3);
root.style.setProperty('--color-text-on-wave', config.styles.colors.textOnWave);
root.style.setProperty('--color-bg-core', config.styles.colors.bgCore);
root.style.setProperty('--color-bg-footer', config.styles.colors.bgFooter);
} }
if(window.location.host.indexOf('locust.kz')>=0){ // This function populates the DOM with content from the config object
window.location.href = "ccalm.org"; function populateContent() {
const content = config[currentLanguage];
document.getElementById('main-title').textContent = content.title;
document.title = content.title;
document.getElementById('intro-text').textContent = content.introText;
document.getElementById('card1-title').textContent = content.card1.title;
const card1Btn = document.getElementById('card1-button');
card1Btn.textContent = content.card1.buttonText;
card1Btn.href = config.urls.asdc;
document.getElementById('card2-title').textContent = content.card2.title;
const card2Btn = document.getElementById('card2-button');
card2Btn.textContent = content.card2.buttonText;
card2Btn.href = config.urls.ccalm;
document.getElementById('footer-contact-title').textContent = content.footer.contactTitle;
const footerPhone = document.getElementById('footer-phone');
footerPhone.textContent = content.footer.phone;
footerPhone.href = config.urls.phone;
const footerEmail = document.getElementById('footer-email');
footerEmail.textContent = content.footer.email;
footerEmail.href = config.urls.email;
document.getElementById('copyright-notice').textContent = `© ${content.footer.copyrightYear} CCALM. All Rights Reserved.`;
} }
document.addEventListener('DOMContentLoaded', () => { // This function switches between languages
const url = new URL(window.location.href); function switchLanguage(lang) {
const message = url.searchParams.get('msg'); currentLanguage = lang;
if (message) { populateContent();
alert2(trt('Alert'),trt(message));
url.searchParams.delete('msg'); // Update active button
window.history.replaceState({}, document.title, url); document.querySelectorAll('.language-button').forEach(btn => {
btn.classList.remove('active');
});
document.getElementById(`lang-${lang}`).classList.add('active');
}
// This function sets up the Intersection Observer for scroll animations
function setupScrollAnimations() {
const sections = document.querySelectorAll('.fade-in-section');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('is-visible');
} }
}); });
}, {
threshold: 0.1 // Trigger when 10% of the element is visible
});
sections.forEach(section => {
observer.observe(section);
});
}
// Run all setup functions when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', () => {
applyStyles();
populateContent();
setupScrollAnimations();
});
</script> </script>
</head>
<body>
<div class='content'> <!-- Language Selector -->
<div class="language-selector">
<div style="padding: 5px; background-color: #ffa100;"><table cellspacing="0" cellpadding="0" border="0" style="width: 100%"><tr><td style="width: 50px;"><a href="/"><img src="./resources/images/locust.png" style="width: 70px;"></a></td><td style="text-align: right; vertical-align: top;"><!--a href="#" onclick="setCookie ('lng', 'en', 365, '', '', ''); window.location.reload();">English</a--></td></tr></table></div> <button id="lang-en" class="language-button active" onclick="switchLanguage('en')">
English
<div style="padding: 5px;"> </button>
<h1 style="text-align: center;">Caucasus and Central Asia Locusts Management system (CCALM)</h1> <button id="lang-ru" class="language-button" onclick="switchLanguage('ru')">
<p style="font-size: 14pt; text-indent: 25px;"> Русский
<img src="./resources/images/locust.png" align="right" style="margin: 5px;"> </button>
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. </div>
</p>
<!--p style="font-size: 14pt; text-indent: 25px;">
To use the "Automated system of data collection" you have to agree to the <a href="#">terms</a> and <a href="#">sign up</a>.
<p-->
<center>
<table border="0"><tr><td style="width: 300px; padding: 20px">
<a target="_blank" href="https://play.google.com/store/apps/details?id=kz.istt.locust"><center>Automated system of data collection (ASDC)<br>
<img src="./resources/images/google_android_download.png"></center></a>
</td><td style="width: 300px; padding: 20px">
<a href="#" onclick="window.open('./engine'); return false;"><center>Caucasus and Central Asia Locusts Management system (CCALM)<br>
<img src="./resources/images/flex.png"></center></a>
</td></tr></table>
</center>
<br>
<center>For any questions contact us at tel./Fax 8(727)3967038, E-mail: <a href="mailto:info@ccalm.org">info@ccalm.org</a>.</center>
<!-- Header Section -->
<header class="wave-header pb-28 pt-10">
<div class="container mx-auto px-6 text-center">
<div class="inline-block bg-white/95 backdrop-blur-md p-6 md:p-10 rounded-xl shadow-2xl">
<h1 id="main-title" class="text-3xl md:text-5xl font-bold text-gray-800"></h1>
</div> </div>
</div> </div>
</header>
<!-- Main Content Section -->
<main class="pb-16 md:pb-20">
<div class="container mx-auto px-6">
<!-- Introductory Text -->
<section class="max-w-4xl mx-auto text-center mb-8 md:mb-12 fade-in-section -mt-16 relative z-10">
<div class="bg-white p-10 rounded-lg shadow-lg">
<p id="intro-text" class="text-lg md:text-xl leading-relaxed text-gray-600"></p>
</div>
</section>
<!-- Feature Cards Section -->
<section class="grid grid-cols-1 md:grid-cols-2 gap-10 lg:gap-16 max-w-5xl mx-auto fade-in-section">
<!-- Card 1: Automated System -->
<div class="info-card flex flex-col items-center p-8 text-center">
<div class="icon-container mb-6">
<i class="ph-bold ph-device-tablet text-5xl"></i>
</div>
<h2 id="card1-title" class="text-xl font-semibold text-gray-700 mb-6 flex-grow"></h2>
<a id="card1-button" href="#" class="btn-custom mt-auto" target="_blank"></a>
</div>
<!-- Card 2: Management System -->
<div class="info-card flex flex-col items-center p-8 text-center">
<div class="icon-container mb-6">
<i class="ph-bold ph-desktop-tower text-5xl"></i>
</div>
<h2 id="card2-title" class="text-xl font-semibold text-gray-700 mb-6 flex-grow"></h2>
<a id="card2-button" href="#" class="btn-custom mt-auto" target="_blank"></a>
</div>
</section>
</div>
</main>
<!-- Footer Section -->
<footer style="background-color: var(--color-bg-footer);" class="text-gray-300 py-12">
<div class="container mx-auto px-6 text-center">
<h3 id="footer-contact-title" class="text-2xl font-semibold mb-6 text-white"></h3>
<div class="flex flex-col md:flex-row justify-center items-center space-y-4 md:space-y-0 md:space-x-8 text-lg">
<a id="footer-phone" href="#" class="flex items-center space-x-3 hover:text-white transition-colors duration-300" target="_blank">
<i class="ph ph-phone"></i>
<span></span>
</a>
<a id="footer-email" href="#" class="flex items-center space-x-3 hover:text-white transition-colors duration-300" target="_blank">
<i class="ph ph-envelope-simple"></i>
<span></span>
</a>
</div>
<div class="mt-10 border-t border-gray-700 pt-6">
<p id="copyright-notice" class="text-sm text-gray-500"></p>
</div>
</div>
</footer>
</body> </body>
</html> </html>

View File

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

View File

@ -1,391 +0,0 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title th:text="${Authorization}">Authorization</title>
<link rel="icon" href="../resources/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="../resources/engine/css/buttons.css?v=8">
<link rel="stylesheet" href="../resources/engine/normalize.css?v=8">
<link rel="stylesheet" type="text/css" href="../resources/engine/index.css?v=14"/>
<link rel="stylesheet" type="text/css" href="../resources/metadata/dbms/dbms.css?v=14"/>
<script type="text/javascript" src="../translation?v=9"></script>
<script type="text/javascript" src="../resources/metadata/dbms/tools.js?v=14"></script>
<script type="text/javascript" src="../resources/metadata/dbms/window.js?v=14"></script>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
flex-direction: column; /* Вертикальная ориентация */
justify-content: center;
align-items: center;
height: 100vh;
}
.login-container {
background-color: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
}
.login-container h2 {
text-align: center;
margin-bottom: 20px;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
font-weight: bold;
display: block;
margin-bottom: 5px;
}
.form-group input {
width: 100%;
padding: 8px;
border-radius: 4px;
border: 1px solid #ccc;
font-size: 14px;
}
.form-group a {
font-size: 12px;
color: #007bff;
text-decoration: none;
}
.form-group a:hover {
text-decoration: underline;
}
.form-group .button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}
.form-group .button:hover {
background-color: #0056b3;
}
.progress-bar {
display: none;
margin-top: 10px;
text-align: center;
}
/* Custom style for checkbox */
.checkbox-group {
display: flex;
align-items: center;
}
.checkbox-group input {
margin-right: 8px;
}
.centered-text {
text-align: center;
font-size: 14px;
color: #333;
margin-top: auto; /* Этот стиль заставит блок с .centered-text быть внизу */
}
.centered-text a {
color: #007bff;
text-decoration: none;
}
.centered-text a:hover {
text-decoration: underline;
}
/* Header styles */
.header {
width: 100%;
background-color: var(--back-color2);
color: white;
padding: 10px;
text-align: center;
position: fixed;
top: 0;
left: 0;
z-index: 100;
}
</style>
</head>
<body>
<div class="header">
<span>Username</span>
</div>
<!-- Блок ниже должен быть по центру вертикали и горизонтали -->
<div>
<div class="login-container" id="loginForm">
<h2 th:text="${Authorization}">Authorization</h2>
<div>
<div class="form-group">
<label for="1_login"><span th:text="${Login}">Login</span> (E-mail):</label>
<input type="text" id="1_login" name="1_login" maxlength="50" th:placeholder="${Enter_login_or_email}">
</div>
<div class="form-group">
<label for="1_password" th:text="${Password}">Password:</label>
<input type="password" id="1_password" name="password" maxlength="33" th:placeholder="${Enter_password}">
</div>
<div class="form-group">
<button id="loginBtn" class="button" th:text="${Log_in}" onclick="authorizeUser()">Log in</button>
</div>
</div>
</div>
<div class="login-container" style="display: none;" id="registrationForm">
<h2 th:text="${Registration}">Registration</h2>
<div>
<div class="form-group">
<label for="3_country_id"><span th:text="${Country}">Country</span> *</label>
<input type="text" id="3_country_id" name="country" maxlength="50" placeholder="Country">
</div>
<div class="form-group">
<label for="3_lastname"><span th:text="${Surname}">Surname</span></label>
<input type="text" id="3_lastname" name="lastname" maxlength="50" placeholder="Surname">
</div>
<div class="form-group">
<label for="3_firstname"><span th:text="${Name}">Name</span> *</label>
<input type="text" id="3_firstname" name="firstname" maxlength="50" placeholder="Name">
</div>
<div class="form-group">
<label for="3_company"><span th:text="${Company}">Company</span></label>
<input type="text" id="3_company" name="company" maxlength="50" placeholder="Company">
</div>
<div class="form-group">
<label for="3_position"><span th:text="${Position}">Position</span></label>
<input type="text" id="3_position" name="position" maxlength="50" placeholder="Position">
</div>
<div class="form-group">
<label for="3_phone"><span th:text="${Phone}">Phone</span></label>
<input type="text" id="3_phone" name="phone" maxlength="50" placeholder="Phone">
</div>
<div class="form-group">
<label for="3_email"><span th:text="${E_mail}">Email</span> *</label>
<input type="text" id="3_email" name="email" maxlength="50" placeholder="E-mail">
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="privacyPolicy" onclick="toggleRegisterButton()">
<label for="privacyPolicy">
Я согласен с <a href="#">политикой конфиденциальности</a>
</label>
</div>
<div class="form-group">
<button id="registerBtn" class="button" th:text="${Registration}" disabled onclick="registrationUser()">Registration</button>
</div>
</div>
</div>
<div class="login-container" style="display: none;" id="recoveryForm">
<h2 th:text="${Password_recovery}">Password_recovery</h2>
<div>
<div class="form-group">
<label for="3_email"><span th:text="${E_mail}">Email</span> *</label>
<input type="text" id="3_email" name="email" maxlength="50" placeholder="E-mail">
</div>
<div class="form-group">
<button id="nextBtn" class="button" th:text="${Next}">Next</button>
</div>
<div class="progress-bar" id="progressBar2">
<span>Загрузка...</span>
</div>
</div>
</div>
<div class="login-container" style="display: none;" id="changeForm">
<h2 th:text="${Password_recovery}">Password_recovery</h2>
<div>
<div class="form-group">
<label for="3_email"><span th:text="${Login}">Login</span> <span th:text="${E_mail}">Email</span></label>
<input type="text" id="3_email" name="email" maxlength="50" placeholder="E-mail">
</div>
<div class="form-group">
<label for="4_oldPassword"><span th:text="${Old_password}">Old_password</span></label>
<input type="text" id="4_oldPassword" name="old_password" maxlength="50" placeholder="E-mail">
</div>
<div class="form-group">
<label for="4_newPassword"><span th:text="${New_password}">New_password</span></label>
<input type="text" id="4_newPassword" name="new_password" maxlength="50" placeholder="E-mail">
</div>
<div class="form-group">
<label for="4_repeatPassword"><span th:text="${Repeat_password}">New_password</span></label>
<input type="text" id="4_repeatPassword" name="repeat_password" maxlength="50" placeholder="Password">
</div>
<div class="form-group">
<button id="4_btn" class="button" th:text="${Change_password}" onclick="changePassword()">Change_password</button>
</div>
</div>
</div>
<div class="login-container" style="display: none;" id="totpForm">
<h2 th:text="${New_totp_key}">New_totp_key</h2>
<div>
<div class="form-group">
<label for="5_email"><span th:text="${Login}">Login</span> (E-mail)</label>
<input type="text" id="5_email" name="email" maxlength="50" placeholder="E-mail">
</div>
<div class="form-group">
<label for="5_password"><span th:text="${Password}">Password</span></label>
<input type="text" id="5_password" name="password" maxlength="50" placeholder="E-mail">
</div>
<div class="form-group">
<label for="5_oldTotp"><span th:text="${Old_totp}">Old_totp</span></label>
<input type="text" id="5_oldTotp" name="Old_totp" maxlength="50" placeholder="E-mail">
</div>
<div class="form-group">
<label for="5_repeatPassword"><span th:text="${New_totp_code}">New_password</span></label>
<input type="text" id="5_repeatPassword" name="repeat_password" maxlength="50" placeholder="Password">
</div>
<div class="form-group">
<button id="5_btn" class="button" th:text="${New_totp_key}" onclick="newTotp()">New_totp_key</button>
</div>
</div>
</div>
<div class="centered-text">
<p><a href="#" onclick="showForm(1);" th:text="${Authorization}">Authorization</a></p>
<p><a href="#" onclick="showForm(2);" th:text="${Create_a_new_user}">Create a new user</a></p>
<p><a href="#" onclick="showForm(3);" th:text="${Password_recovery}">Password recovery</a></p>
<p><a href="#" onclick="showForm(4);" th:text="${Change_password}">Change password</a></p>
<p><a href="#" onclick="showForm(5);" th:text="${Get_new_TOTP_key}">Get new TOTP key</a></p>
</div>
</div>
<script>
// Функция для отображения формы авторизации
function showForm(num) {
document.getElementById('loginForm').style.display = num === 1 ? 'block' : 'none';
document.getElementById('registrationForm').style.display = num === 2 ? 'block' : 'none';
document.getElementById('recoveryForm').style.display = num === 3 ? 'block' : 'none';
document.getElementById('changeForm').style.display = num === 4 ? 'block' : 'none';
document.getElementById('totpForm').style.display = num === 5 ? 'block' : 'none';
}
// Функция для включения/выключения кнопки регистрации в зависимости от состояния галочки
function toggleRegisterButton() {
const checkbox = document.getElementById('privacyPolicy');
const registerBtn = document.getElementById('registerBtn');
registerBtn.disabled = !checkbox.checked;
}
// Функция для обработки авторизации
function authorizeUser() {
const login = document.getElementById('1_login').value;
const password = document.getElementById('1_password').value;
const obj = {login, password, appid: 'ccalm'};
postJsonData('/api/authorization/v02/login', obj, (ok, data) => {
if (ok) {
if (data.error_code == 0) {
window.location.href = "/engine";
} else {
errorDialog(data)
}
} else {
alert2(trt('Alert'), trt('Error: Unable to authorize.'));
}
});
}
function registrationUser() {
const login = document.getElementById('1_login').value;
const password = document.getElementById('1_password').value;
const obj = {login, password, appid: 'ccalm'};
postJsonData('/api/authorization/v02/login', obj, (ok, data) => {
if (ok) {
if (data.error_code == 0) {
window.location.href = "/engine";
} else {
errorDialog(data)
}
} else {
alert2(trt('Alert'), trt('Error: Unable to authorize.'));
}
});
}
function changePassword() {
const login = document.getElementById('1_login').value;
const password = document.getElementById('1_password').value;
const obj = {login, password, appid: 'ccalm'};
postJsonData('/api/authorization/v02/login', obj, (ok, data) => {
if (ok) {
if (data.error_code == 0) {
window.location.href = "/engine";
} else {
errorDialog(data)
}
} else {
alert2(trt('Alert'), trt('Error: Unable to authorize.'));
}
});
}
function newTotp() {
const login = document.getElementById('1_login').value;
const password = document.getElementById('1_password').value;
const obj = {login, password, appid: 'ccalm'};
postJsonData('/api/authorization/v02/login', obj, (ok, data) => {
if (ok) {
if (data.error_code == 0) {
window.location.href = "/engine";
} else {
errorDialog(data)
}
} else {
alert2(trt('Alert'), trt('Error: Unable to authorize.'));
}
});
}
// Изначально показываем форму авторизации
//showLoginForm();
</script>
</body>
</html>

View File

@ -8,18 +8,18 @@
<meta name="yandex-verification" content="2cb5374be0668fe9" /> <meta name="yandex-verification" content="2cb5374be0668fe9" />
<script type="text/javascript" src="./resources/metadata/jquery.js"></script> <script type="text/javascript" src="./resources/metadata/jquery.js"></script>
<script type="text/javascript" src="./translation?v=7"></script> <script type="text/javascript" src="/api/translation/v01/array"></script>
<script src="./resources/metadata/dbms/tools.js?v=9"></script> <script src="./resources/metadata/dbms/tools.js?v=10"></script>
<script src="./resources/metadata/dbms/window.js?v=10"></script> <script src="./resources/metadata/dbms/window.js?v=11"></script>
<link rel="stylesheet" href="./resources/engine/css/buttons.css?v=7"> <link rel="stylesheet" href="./resources/engine/css/buttons.css?v=8">
<link rel="stylesheet" href="./resources/engine/normalize.css?v=7"> <link rel="stylesheet" href="./resources/engine/normalize.css?v=8">
<link rel="stylesheet" href="./resources/metadata/dbms/dbms.css?v=7"/> <link rel="stylesheet" href="./resources/metadata/dbms/dbms.css?v=8"/>
<link rel="stylesheet" href="./resources/engine/index.css?v=7"> <link rel="stylesheet" href="./resources/engine/index.css?v=8">
<script type="text/javascript" src="./resources/engine/popup.js?v=03"></script> <script type="text/javascript" src="./resources/engine/popup.js?v=04"></script>
<script type="text/javascript" src="./resources/index.js?v=01"></script> <script type="text/javascript" src="./resources/index.js?v=02"></script>
<link rel="stylesheet" href="./resources/engine/openlayers/ol.css" type="text/css"> <link rel="stylesheet" href="./resources/engine/openlayers/ol.css" type="text/css">
<link rel="stylesheet" href="./resources/engine/openlayers/ol-ext.css" /> <link rel="stylesheet" href="./resources/engine/openlayers/ol-ext.css" />