Preparing for the transition to REST API
This commit is contained in:
@ -10,8 +10,9 @@ spring:
|
||||
application:
|
||||
name: org-ccalm-main
|
||||
datasource:
|
||||
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
|
||||
#url: jdbc:postgresql://127.0.0.1:5432/CCALM?ApplicationName=org_ccalm_main&ssl=true&sslmode=require&connectTimeout=10000&socketTimeout=10000
|
||||
username: postgres
|
||||
password: 309A86FF65A78FB428F4E38DFE35F730
|
||||
driver-class-name: org.postgresql.Driver
|
||||
|
||||
12
pom.xml
12
pom.xml
@ -10,7 +10,7 @@
|
||||
</parent>
|
||||
<groupId>org.ccalm</groupId>
|
||||
<artifactId>main</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<version>1.0.1</version>
|
||||
<name>main</name>
|
||||
<description>main</description>
|
||||
<properties>
|
||||
@ -44,12 +44,12 @@
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<!--dependency>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>6.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependency-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jdbc</artifactId>
|
||||
@ -57,7 +57,7 @@
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>42.7.5</version>
|
||||
<version>42.7.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
@ -143,10 +143,10 @@
|
||||
<version>1.18.36</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>org-ccalm-main</finalName>
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
@ -163,7 +163,7 @@
|
||||
<version>2.22.2</version>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<spring.config.location>file:application.properties</spring.config.location>
|
||||
<spring.config.location>file:org-ccalm-main.yml</spring.config.location>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
12
src/main/java/logging/Logger.java
Normal file
12
src/main/java/logging/Logger.java
Normal 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); // Подменяется реализацией
|
||||
}
|
||||
}
|
||||
22
src/main/java/logging/LoggerFactory.java
Normal file
22
src/main/java/logging/LoggerFactory.java
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
18
src/main/java/logging/SLF4JLogger.java
Normal file
18
src/main/java/logging/SLF4JLogger.java
Normal 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); }
|
||||
}
|
||||
@ -134,7 +134,7 @@ public class AcceptASDCController implements ServletContextAware {
|
||||
}
|
||||
|
||||
//Update lon lat
|
||||
@RequestMapping(value = "/update",method = { RequestMethod.GET })
|
||||
@RequestMapping(value = {"/update", "/api/locust/v01/update"},method = { RequestMethod.GET })
|
||||
@ResponseBody
|
||||
public Object update_lon_lat() {
|
||||
JSONObject result = new JSONObject();
|
||||
@ -233,7 +233,7 @@ public class AcceptASDCController implements ServletContextAware {
|
||||
}
|
||||
|
||||
//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
|
||||
public Object uploadFrmLocustHealth(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestBody(required=false) byte[] reqData) {
|
||||
JSONObject result = new JSONObject();
|
||||
@ -889,7 +889,7 @@ public class AcceptASDCController implements ServletContextAware {
|
||||
}
|
||||
|
||||
// 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
|
||||
public Object uploadJSON(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestBody(required=false) byte[] reqData) {
|
||||
|
||||
@ -1050,7 +1050,7 @@ public class AcceptASDCController implements ServletContextAware {
|
||||
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
|
||||
public Object uploadXML(HttpServletResponse response, @RequestHeader(required=false,name="Content-Type") String contentType, @RequestBody(required=false) byte[] reqData) {
|
||||
|
||||
@ -2496,7 +2496,7 @@ public class AcceptASDCController implements ServletContextAware {
|
||||
}
|
||||
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
|
||||
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) {
|
||||
|
||||
@ -2699,7 +2699,7 @@ public class AcceptASDCController implements ServletContextAware {
|
||||
* @param reqData
|
||||
* @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
|
||||
public Object uploadTCTable(@RequestHeader(required=false,name="Content-Type") String contentType,@RequestParam(required=false,name="file") MultipartFile file) {
|
||||
|
||||
@ -3032,7 +3032,7 @@ public class AcceptASDCController implements ServletContextAware {
|
||||
}
|
||||
|
||||
//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
|
||||
public FileSystemResource sendPhoto(HttpServletResponse response,@RequestParam(required=true,name="table") String tableName,@RequestParam(required=true,name="file") String fileName) {
|
||||
|
||||
@ -3068,9 +3068,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
|
||||
public Object getPhotoList() {
|
||||
|
||||
|
||||
@ -65,7 +65,7 @@ public class AcceptEXCEL implements ServletContextAware {
|
||||
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) {
|
||||
|
||||
Connection conn = null;
|
||||
|
||||
@ -44,6 +44,7 @@ import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
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.Value;
|
||||
import org.springframework.core.env.Environment;
|
||||
@ -121,7 +122,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
* @return
|
||||
*/
|
||||
@ResponseBody
|
||||
@RequestMapping(value = "/AcceptJSON_KAZ", method = { RequestMethod.GET, RequestMethod.POST })
|
||||
@RequestMapping(value = {"/AcceptJSON_KAZ", "/api/locust/v01/AcceptJSON_KAZ"}, method = { RequestMethod.GET, RequestMethod.POST })
|
||||
public String acceptJSON_KAZ(@ModelAttribute User user, Model model,@RequestParam(required=false,name="file") MultipartFile file,@RequestParam(required=false,name="skip",defaultValue = "0") Boolean skip) {
|
||||
|
||||
//TODO add user verification: that he is authorized and that he is an administrator!
|
||||
@ -427,7 +428,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
* @param skip
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "/AcceptJSON_RUS", method = { RequestMethod.GET, RequestMethod.POST })
|
||||
@RequestMapping(value = {"/AcceptJSON_RUS", "/api/locust/v01/AcceptJSON_RUS"}, method = { RequestMethod.GET, RequestMethod.POST })
|
||||
public String acceptCSV(@ModelAttribute User user, Model model,@RequestParam(required=false,name="file") MultipartFile file,@RequestParam(required=false,name="skip",defaultValue = "0") Boolean skip) {
|
||||
|
||||
Connection conn = null;
|
||||
@ -1398,7 +1399,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
//---------------------------------------------------------------------------
|
||||
//https://127.0.0.1:8081/AcceptJSON_UZB
|
||||
@ResponseBody
|
||||
@RequestMapping(value = "/AcceptJSON_UZB", method = { RequestMethod.GET, RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@RequestMapping(value = {"/AcceptJSON_UZB", "/api/locust/v01/AcceptJSON_UZB"}, method = { RequestMethod.GET, RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public String acceptUZB(@ModelAttribute User user) {
|
||||
JSONObject json = new JSONObject();
|
||||
try{
|
||||
@ -1450,7 +1451,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
if (response.statusCode() / 100 == 2) { // 2xx — успешные коды
|
||||
content = response.body();
|
||||
} else {
|
||||
throw new CustomException(10000, "Error download data from: " + strURL,null,true);
|
||||
throw new CustomException(200, 10000, "Error download data from: " + strURL,null,true);
|
||||
}
|
||||
|
||||
if(content!=null && !content.isEmpty()) {
|
||||
@ -2324,14 +2325,14 @@ public class AcceptJSON implements ServletContextAware {
|
||||
}
|
||||
|
||||
} catch (CustomException e) {
|
||||
if(e.isSaveToLog()){
|
||||
if(e.isSaveToLog()) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e);
|
||||
}
|
||||
json = e.getJson();
|
||||
} catch (Exception e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e);
|
||||
json = Tools.createJSONError(10000,"Internal_Server_Error", (String)null, uuid);
|
||||
}
|
||||
return json.toString();
|
||||
@ -2442,7 +2443,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
break;
|
||||
default:
|
||||
System.out.println(obj.optString("region_name",null));
|
||||
throw new CustomException(10000, "Not find region by region_name: " + obj.optString("region_name",null), null, true);
|
||||
throw new CustomException(200, 10000, "Not find region by region_name: " + obj.optString("region_name",null), null, true);
|
||||
}
|
||||
}
|
||||
result.district = obj.optString("town_name",null);
|
||||
@ -2522,7 +2523,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.bio_biotope_uid = "e99a8868-2582-41e8-9c01-bef5fca8f0d1";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find biotope_type: " + obj.optString("biotope_type",null), null, true);
|
||||
throw new CustomException(200, 10000, "Not find biotope_type: " + obj.optString("biotope_type",null), null, true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2550,7 +2551,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.bio_greenery_uid = "682993e1-3e5b-4aa0-9f11-c2a30a9c5908";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find vegetation: " + obj.optString("vegetation",null), null, true);
|
||||
throw new CustomException(200, 10000, "Not find vegetation: " + obj.optString("vegetation",null), null, true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2574,7 +2575,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.bio_greenery_cover_uid = "f712fe9a-2e42-44b9-b3dc-a7a1dc4767e8";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find vegetation_cover: " + obj.optString("vegetation_cover",null), null, true);
|
||||
throw new CustomException(200, 10000, "Not find vegetation_cover: " + obj.optString("vegetation_cover",null), null, true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2612,7 +2613,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.locust_type_uid = "bf79cae1-1e01-4e7f-8ec1-deb06936a58e";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find subject_name: " + obj.optString("subject_name",null), null, true);
|
||||
throw new CustomException(200, 10000, "Not find subject_name: " + obj.optString("subject_name",null), null, true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2647,7 +2648,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.eggs_enemies_uid = "d0cf06f4-6e1f-4da2-b836-45dfdef5da98";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find eggs_natural_enemies: " + obj.optString("eggs_natural_enemies",null), null, true);
|
||||
throw new CustomException(200, 10000, "Not find eggs_natural_enemies: " + obj.optString("eggs_natural_enemies",null), null, true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2663,7 +2664,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.larva_born_uid="3210fcfb-3885-4b0e-92c7-3c6f6a0b7134";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find hoppers_hatching: " + obj.optString("hoppers_hatching",null),null,true);
|
||||
throw new CustomException(200, 10000, "Not find hoppers_hatching: " + obj.optString("hoppers_hatching",null),null,true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2711,7 +2712,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.larva_age_uid="683cdba3-2f4c-4e61-b667-936c524136b4";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find hoppers_stages: " + obj.optString("hoppers_stages",null),null,true);
|
||||
throw new CustomException(200, 10000, "Not find hoppers_stages: " + obj.optString("hoppers_stages",null),null,true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2731,7 +2732,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.larva_behavior_uid="bc8c7de0-0e79-4b40-8260-a74787e19902";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find hoppers_spatial_distribution: " + obj.optString("hoppers_spatial_distribution",null),null,true);
|
||||
throw new CustomException(200, 10000, "Not find hoppers_spatial_distribution: " + obj.optString("hoppers_spatial_distribution",null),null,true);
|
||||
}
|
||||
}
|
||||
result.larva_density = obj.optString("hoppers_density_from_m2",null); //Hopper density numeric,
|
||||
@ -2764,7 +2765,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.kuliguli_action_uid="65bf377f-040b-4b5f-8dca-581e1d5d679f";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find bands_behaviour: " + obj.optString("bands_behaviour",null),null,true);
|
||||
throw new CustomException(200, 10000, "Not find bands_behaviour: " + obj.optString("bands_behaviour",null),null,true);
|
||||
}
|
||||
}
|
||||
/*if(!obj.isNull("bands_stages") && !obj.optString("bands_stages","").isBlank()){
|
||||
@ -2808,7 +2809,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.imago_phase_uid="5a7cacb9-c0f5-48e1-aa8c-c354565bf2f1";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find bands_stages: " + obj.optString("bands_stages",null),null,true);
|
||||
throw new CustomException(200, 10000, "Not find bands_stages: " + obj.optString("bands_stages",null),null,true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2824,7 +2825,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.imago_wing_uid="97d5a02c-c3ed-4627-ae14-4f92d6eb2945";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find adults_fledging: " + obj.optString("adults_fledging",null),null,true);
|
||||
throw new CustomException(200, 10000, "Not find adults_fledging: " + obj.optString("adults_fledging",null),null,true);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2850,7 +2851,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.imago_action_uid="c120254b-cbb9-415a-8e41-fc4bb0ffe983";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find adults_spatial_distribution: " + obj.optString("adults_spatial_distribution",null),null,true);
|
||||
throw new CustomException(200, 10000, "Not find adults_spatial_distribution: " + obj.optString("adults_spatial_distribution",null),null,true);
|
||||
}
|
||||
}
|
||||
result.imago_density = obj.optString("adults_density_m2",null);
|
||||
@ -2908,7 +2909,7 @@ public class AcceptJSON implements ServletContextAware {
|
||||
result.swarm_height_uid = "305d3224-ac2e-4abe-8adc-058373f20127";
|
||||
break;
|
||||
default:
|
||||
throw new CustomException(10000, "Not find swarms_height: (" + obj.optString("swarms_height",null)+")", null, true);
|
||||
throw new CustomException(200, 10000, "Not find swarms_height: (" + obj.optString("swarms_height",null)+")", null, true);
|
||||
}
|
||||
}
|
||||
result.description = obj.optString("description",null);
|
||||
|
||||
@ -64,7 +64,7 @@ public class DataJSON implements ServletContextAware {
|
||||
// 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
|
||||
public String getCompanies(@ModelAttribute User user,@RequestParam(required=false,name="country_id") String country_id,@RequestParam(required=false,name="lng") String language_id) {
|
||||
|
||||
|
||||
@ -30,7 +30,7 @@ public class DownloadNDVI implements ServletContextAware {
|
||||
|
||||
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
|
||||
public Object ajaxTamer(@RequestParam(required=false,name="forecast") String forecast) {
|
||||
|
||||
|
||||
@ -51,7 +51,7 @@ public class DownloadWeather implements ServletContextAware {
|
||||
@Value("${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
|
||||
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".
|
||||
@ -354,7 +354,7 @@ public class DownloadWeather implements ServletContextAware {
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
//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
|
||||
public Object ajaxSoilDates() {
|
||||
boolean error=false;
|
||||
|
||||
@ -47,7 +47,7 @@ public class GeoGSON implements ServletContextAware {
|
||||
@Value("${data.dir}")
|
||||
String data_dir = "";
|
||||
|
||||
@RequestMapping(value = "/geojson", method = RequestMethod.GET)
|
||||
@RequestMapping(value = {"/geojson", "/api/locust/v01/geojson"}, method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
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
|
||||
//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
|
||||
public Object countriesregions()
|
||||
{
|
||||
|
||||
48
src/main/java/org/ccalm/main/GlobalExceptionHandler.java
Normal file
48
src/main/java/org/ccalm/main/GlobalExceptionHandler.java
Normal 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);
|
||||
}
|
||||
}
|
||||
@ -58,7 +58,7 @@ public class Integration implements ServletContextAware {
|
||||
@Value("${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
|
||||
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);
|
||||
}
|
||||
|
||||
@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
|
||||
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
|
||||
public Object getPhoto(@RequestParam(required=true,name="token") String token,@RequestParam(required=true,name="id") Long id)
|
||||
{
|
||||
|
||||
@ -61,7 +61,7 @@ public class MainController implements ServletContextAware {
|
||||
/**
|
||||
* 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) {
|
||||
logger.info("Welcome home! The client locale is {}.", locale);
|
||||
|
||||
@ -73,7 +73,7 @@ public class MainController implements ServletContextAware {
|
||||
return "privacy";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/robots.txt")
|
||||
@RequestMapping(value = {"/robots.txt", "/api/locust/v01/robots.txt"})
|
||||
public void robots(HttpServletResponse response) {
|
||||
try {
|
||||
response.getWriter().write("User-agent: *\n");
|
||||
@ -87,7 +87,7 @@ public class MainController implements ServletContextAware {
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/sitemap.xml")
|
||||
@RequestMapping(value = {"/sitemap.xml", "/api/locust/v01/sitemap.xml"})
|
||||
public void sitemap(HttpServletResponse response) {
|
||||
try {
|
||||
response.getWriter().write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
|
||||
@ -104,7 +104,7 @@ public class MainController implements ServletContextAware {
|
||||
/**
|
||||
* 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) {
|
||||
int language_id;
|
||||
try {
|
||||
@ -120,12 +120,12 @@ public class MainController implements ServletContextAware {
|
||||
//Для перевода выбираю всё что под номером 1 в переводе
|
||||
TranslationUtils.loadTranslations(jdbcTemplate, language_id, model);
|
||||
|
||||
//return "index";
|
||||
return "test";
|
||||
return "index";
|
||||
//return "test";
|
||||
}
|
||||
|
||||
//Returns data for building a map on the first index page
|
||||
@RequestMapping(value = "/dataindex",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json; charset=utf-8")
|
||||
@RequestMapping(value = {"/dataindex", "/api/locust/v01/dataindex"},method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json; charset=utf-8")
|
||||
@ResponseBody
|
||||
public Object ajaxIndexData(HttpServletResponse response,@ModelAttribute User user,@RequestParam(required=false,name="date_start") 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();
|
||||
|
||||
@ -5,32 +5,37 @@ import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Properties;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
//import javax.servlet.ServletContext;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
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 org.ccalm.main.models.ErrorResponseModel;
|
||||
import org.ccalm.main.utils.CustomException;
|
||||
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.Value;
|
||||
import org.springframework.core.env.Environment;
|
||||
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.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.SessionAttributes;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.context.ServletContextAware;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
@ -40,7 +45,10 @@ import org.json.JSONObject;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
|
||||
import tctable.Tools;
|
||||
import tools.DBTools;
|
||||
import tools.PreparedStatementNamed;
|
||||
import tools.Translation;
|
||||
import tools.User;
|
||||
|
||||
@Controller
|
||||
@ -57,20 +65,52 @@ public class Products implements ServletContextAware {
|
||||
String db_login="";
|
||||
@Value("${spring.datasource.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.
|
||||
//@ModelAttribute("user")
|
||||
//public User populatePerson() {
|
||||
// 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
|
||||
public String getLocustSurvey(@ModelAttribute User user,@RequestBody(required=false) byte[] reqData,@RequestParam(required=false,name="lng") String language_id) {
|
||||
|
||||
int errorCode=0;
|
||||
String errorMessage="";
|
||||
public ResponseEntity<Object> getLocustSurvey(
|
||||
@ModelAttribute User user,
|
||||
@RequestBody(required=false) 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;
|
||||
try {
|
||||
@ -79,13 +119,10 @@ public class Products implements ServletContextAware {
|
||||
if (conn != null) {
|
||||
logger.info("Connect is OK!");
|
||||
} else {
|
||||
errorCode=1;
|
||||
errorMessage+="An error occurred while connecting to the database!";
|
||||
throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.info(ex.getMessage());
|
||||
errorCode=1;
|
||||
errorMessage+="An error occurred while connecting to the database!";
|
||||
throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
|
||||
}
|
||||
|
||||
try {
|
||||
@ -94,9 +131,7 @@ public class Products implements ServletContextAware {
|
||||
stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем раскоментил? может в начале поставить ещё TimeZone.setDefault(TimeZone.getTimeZone("UTC")); ?
|
||||
stt0.close();
|
||||
} catch (SQLException ex) {
|
||||
logger.info(ex.getMessage());
|
||||
errorCode=1;
|
||||
errorMessage+="Failed to execute SQL query!";
|
||||
throw new CustomException(200, 10000, trt.trt(false, "Failed to execute SQL query!"), UUID.randomUUID().toString(),true);
|
||||
}
|
||||
|
||||
JSONObject doc=null;
|
||||
@ -344,46 +379,66 @@ public class Products implements ServletContextAware {
|
||||
}
|
||||
rs.close();
|
||||
} catch (SQLException ex) {
|
||||
errorCode=4;
|
||||
errorMessage+="Internal server error, sampling.";
|
||||
ex.printStackTrace();
|
||||
logger.info(ex.getMessage());
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
|
||||
throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
errorCode=5;
|
||||
errorMessage+="Внутренняя ошибка сервера, запрос. ";
|
||||
ex.printStackTrace();
|
||||
logger.info(ex.getMessage());
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
|
||||
throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
|
||||
}finally {
|
||||
if(rs!=null) try{rs.close();}catch(SQLException ex){}
|
||||
if(stt!=null) try{stt.close();}catch(SQLException ex){}
|
||||
}
|
||||
|
||||
|
||||
if(errorCode!=0) {
|
||||
JSONObject obj = new JSONObject();
|
||||
obj.put("error_code",errorCode);
|
||||
obj.put("error_message", errorMessage);
|
||||
return obj.toString();
|
||||
}else {
|
||||
JSONObject obj = new JSONObject();
|
||||
obj.put("error_code",0);
|
||||
obj.put("error_message", "");
|
||||
if(doc!=null)
|
||||
obj.put("indicator",doc.getString("indicator"));
|
||||
obj.put("data",array);
|
||||
return obj.toString();
|
||||
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",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
|
||||
@RequestMapping(value = {"/get_spray", "/api/locust/v01/get_spray"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
|
||||
@ResponseBody
|
||||
public String getSprayMonitoring(@ModelAttribute User user,@RequestBody byte[] reqData,@RequestParam(required=false,name="lng") String language_id) {
|
||||
|
||||
int errorCode=0;
|
||||
String errorMessage="";
|
||||
public ResponseEntity<Object> getSprayMonitoring(
|
||||
@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;
|
||||
try {
|
||||
@ -392,13 +447,10 @@ public class Products implements ServletContextAware {
|
||||
if (conn != null) {
|
||||
logger.info("Connect is OK!");
|
||||
} else {
|
||||
errorCode=1;
|
||||
errorMessage+="An error occurred while connecting to the database!";
|
||||
throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.info(ex.getMessage());
|
||||
errorCode=1;
|
||||
errorMessage+="An error occurred while connecting to the database!";
|
||||
throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
|
||||
}
|
||||
|
||||
try {
|
||||
@ -407,9 +459,7 @@ public class Products implements ServletContextAware {
|
||||
stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';");
|
||||
stt0.close();
|
||||
} catch (SQLException ex) {
|
||||
logger.info(ex.getMessage());
|
||||
errorCode=1;
|
||||
errorMessage+="Failed to execute SQL query!";
|
||||
throw new CustomException(200, 10000, trt.trt(false, "Failed to execute SQL query!"), UUID.randomUUID().toString(),true);
|
||||
}
|
||||
|
||||
JSONObject doc=null;
|
||||
@ -625,43 +675,150 @@ public class Products implements ServletContextAware {
|
||||
}
|
||||
rs.close();
|
||||
} catch (SQLException ex) {
|
||||
errorCode=4;
|
||||
errorMessage+="Internal server error, sampling.";
|
||||
ex.printStackTrace();
|
||||
logger.info(ex.getMessage());
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
|
||||
throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
errorCode=5;
|
||||
errorMessage+="Внутренняя ошибка сервера, запрос. ";
|
||||
ex.printStackTrace();
|
||||
logger.info(ex.getMessage());
|
||||
throw new CustomException(200, 10000, trt.trt(false, "Internal server error."), UUID.randomUUID().toString(),true);
|
||||
}finally {
|
||||
if(rs!=null) try{rs.close();}catch(SQLException ex){}
|
||||
if(stt!=null) try{stt.close();}catch(SQLException ex){}
|
||||
}
|
||||
|
||||
|
||||
if(errorCode!=0) {
|
||||
JSONObject obj = new JSONObject();
|
||||
obj.put("error_code",errorCode);
|
||||
obj.put("error_message", errorMessage);
|
||||
return obj.toString();
|
||||
}else {
|
||||
JSONObject obj = new JSONObject();
|
||||
obj.put("error_code",0);
|
||||
obj.put("error_message", "");
|
||||
obj.put("data",array);
|
||||
return obj.toString();
|
||||
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
|
||||
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;
|
||||
String errorMessage="";
|
||||
JSONObject doc=null;
|
||||
InputStream body;
|
||||
if(reqData!=null) {
|
||||
body = new ByteArrayInputStream(reqData);
|
||||
String text="";
|
||||
try {
|
||||
text = new String(body.readAllBytes(), StandardCharsets.UTF_8);
|
||||
} catch (IOException 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;
|
||||
try {
|
||||
@ -670,13 +827,10 @@ public class Products implements ServletContextAware {
|
||||
if (conn != null) {
|
||||
logger.info("Connect is OK!");
|
||||
} else {
|
||||
errorCode=1;
|
||||
errorMessage+="An error occurred while connecting to the database!";
|
||||
throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.info(ex.getMessage());
|
||||
errorCode=1;
|
||||
errorMessage+="An error occurred while connecting to the database!";
|
||||
throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true);
|
||||
}
|
||||
|
||||
try {
|
||||
@ -685,9 +839,7 @@ public class Products implements ServletContextAware {
|
||||
stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';");
|
||||
stt0.close();
|
||||
} catch (SQLException ex) {
|
||||
logger.info(ex.getMessage());
|
||||
errorCode=1;
|
||||
errorMessage+="Failed to execute SQL query!";
|
||||
throw new CustomException(200, 10000, trt.trt(false, "Failed to execute SQL query!"), UUID.randomUUID().toString(),true);
|
||||
}
|
||||
|
||||
JSONObject doc=null;
|
||||
@ -727,7 +879,8 @@ public class Products implements ServletContextAware {
|
||||
f.lon,
|
||||
f.radius,
|
||||
f.name,
|
||||
f.temperature
|
||||
f.temperature_soil,
|
||||
f.temperature_air
|
||||
from
|
||||
main.frmcheckpoints f
|
||||
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("lon", lon);
|
||||
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);
|
||||
}
|
||||
rs.close();
|
||||
} catch (SQLException ex) {
|
||||
errorCode=4;
|
||||
errorMessage+="Internal server error, sampling.";
|
||||
ex.printStackTrace();
|
||||
logger.info(ex.getMessage());
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
|
||||
throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
errorCode=5;
|
||||
errorMessage+="Internal server error, sampling. ";
|
||||
ex.printStackTrace();
|
||||
logger.info(ex.getMessage());
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(MarkerFactory.getMarker(uuid), ex.getMessage());
|
||||
throw new CustomException(200, 10000, trt.trt(false, "Internal_server_error"), UUID.randomUUID().toString(),false);
|
||||
}finally {
|
||||
if(rs!=null) try{rs.close();}catch(SQLException ex){}
|
||||
if(stt!=null) try{stt.close();}catch(SQLException ex){}
|
||||
}
|
||||
|
||||
|
||||
if(errorCode!=0) {
|
||||
JSONObject obj = new JSONObject();
|
||||
obj.put("error_code",errorCode);
|
||||
obj.put("error_message", errorMessage);
|
||||
return obj.toString();
|
||||
}else {
|
||||
JSONObject obj = new JSONObject();
|
||||
obj.put("error_code",0);
|
||||
obj.put("error_message", "");
|
||||
obj.put("data",array);
|
||||
return obj.toString();
|
||||
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_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
|
||||
public String getDensityLarval(@ModelAttribute User user,@RequestBody byte[] reqData,@RequestParam(required=false,name="id") Integer id,@RequestParam(required=false,name="lng") String language_id) {
|
||||
int errorCode=0;
|
||||
String errorMessage="";
|
||||
|
||||
Connection conn = null;
|
||||
public ResponseEntity<Object> getDensityLarval(
|
||||
@ModelAttribute User user,
|
||||
@RequestBody byte[] reqData,
|
||||
@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 {
|
||||
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!";
|
||||
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);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.info(ex.getMessage());
|
||||
errorCode=1;
|
||||
errorMessage+="An error occurred while connecting to the database!";
|
||||
user.id = claims.getBody().get("user_id").toString();
|
||||
}
|
||||
|
||||
try {
|
||||
Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
|
||||
stt0.executeUpdate("SET TIME ZONE 'UTC';"); //зачем коментил?
|
||||
//stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем нужно вообще?
|
||||
stt0.close();
|
||||
} catch (SQLException ex) {
|
||||
logger.info(ex.getMessage());
|
||||
errorCode=1;
|
||||
errorMessage+="Failed to execute SQL query!";
|
||||
}
|
||||
|
||||
|
||||
JSONArray array=new JSONArray(); //Результирующий набор данных
|
||||
|
||||
String sql_query = "";
|
||||
Statement stt=null;
|
||||
ResultSet rs=null;
|
||||
try {
|
||||
stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
|
||||
sql_query = """
|
||||
select * from main.get_density_larval(${id});
|
||||
String sql_query = """
|
||||
select * from main.get_density_larval(:id);
|
||||
""";
|
||||
PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query);
|
||||
stmtn.setInt("id",id);
|
||||
PreparedStatement stmt=stmtn.getPreparedStatement();
|
||||
|
||||
rs = stmt.executeQuery();
|
||||
if (rs != null) {
|
||||
try {
|
||||
while(rs.next()) {
|
||||
JSONObject obj = new JSONObject();
|
||||
obj.put("year", rs.getLong(1));
|
||||
obj.put("density", rs.getFloat(2));
|
||||
array.put(obj);
|
||||
}
|
||||
rs.close();
|
||||
} catch (SQLException ex) {
|
||||
errorCode=1;
|
||||
errorMessage+="Internal server error";
|
||||
ex.printStackTrace();
|
||||
logger.info(ex.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
errorCode=1;
|
||||
errorMessage+="Internal server error";
|
||||
ex.printStackTrace();
|
||||
logger.info(ex.getMessage());
|
||||
}finally {
|
||||
if(rs!=null) try{rs.close();}catch(SQLException ex){}
|
||||
if(stt!=null) try{stt.close();}catch(SQLException ex){}
|
||||
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);
|
||||
}
|
||||
|
||||
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();
|
||||
obj.put("error_code",0);
|
||||
obj.put("error_message", "");
|
||||
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
|
||||
public void setServletContext(ServletContext 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;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
}
|
||||
|
||||
@ -66,7 +66,7 @@ public class QGIS implements ServletContextAware {
|
||||
// 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
|
||||
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)
|
||||
{
|
||||
|
||||
@ -67,7 +67,7 @@ public class SendMail implements ServletContextAware {
|
||||
// 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
|
||||
public Object send(@ModelAttribute User user,@RequestParam(required=false,name="lng") String language_id) {
|
||||
|
||||
|
||||
@ -3,6 +3,7 @@ package org.ccalm.main;
|
||||
import jakarta.servlet.ServletContext;
|
||||
import org.json.JSONObject;
|
||||
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.http.*;
|
||||
@ -47,7 +48,7 @@ public class SendWarning {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
public JSONObject getSoilTemperature(double lat,double lon){
|
||||
public JSONObject getAirTemperature(double lat,double lon){
|
||||
JSONObject result=null;
|
||||
// Формируем JSON-запрос
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
@ -73,12 +74,43 @@ public class SendWarning {
|
||||
}
|
||||
} catch (Exception e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
@RequestMapping(value = {"/api/locust/v01/SendWarning"},method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<Object> send() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
@ -91,27 +123,33 @@ public class SendWarning {
|
||||
t.user_uid,
|
||||
t.lat,
|
||||
t.lon,
|
||||
t.temperature as value,
|
||||
u.email,
|
||||
l.short_name
|
||||
l.short_name,
|
||||
t.temperature_air,
|
||||
t.warn_air,
|
||||
t.temperature_soil,
|
||||
t.warn_soil
|
||||
from
|
||||
main.frmcheckpoints t
|
||||
join main._users u on u.uid=t.user_uid
|
||||
join main._languages l on l.uid=u.language_uid
|
||||
where
|
||||
t.del=false
|
||||
and t.warn=true
|
||||
and (t.warn_soil=true or t.warn_air=true)
|
||||
""";
|
||||
MapSqlParameterSource parameters = new MapSqlParameterSource();
|
||||
//parameters.addValue("language_id", language_id, Types.INTEGER);
|
||||
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
||||
for (String jsonString : ret) {
|
||||
JSONObject obj = new JSONObject(jsonString);
|
||||
JSONObject tmp = getSoilTemperature(obj.getDouble("lat"),obj.getDouble("lon"));
|
||||
if(tmp!=null) {
|
||||
|
||||
JSONObject tmp_soil = getSoilTemperature(obj.getDouble("lat"),obj.getDouble("lon"));
|
||||
JSONObject tmp_air = getAirTemperature(obj.getDouble("lat"),obj.getDouble("lon"));
|
||||
|
||||
if(tmp_air!=null) {
|
||||
Translation trt=new Translation(obj.getString("short_name"),jdbcTemplate);
|
||||
double value = obj.getDouble("value");
|
||||
if (value < tmp.getDouble("value")) {
|
||||
if (value < tmp_air.getDouble("value")) {
|
||||
String email = obj.getString("email");
|
||||
if(email.equals("irigm@mail.ru") || email.equals("ivanov.i@istt.kz")){ //TODO для тестирования потом удалить
|
||||
|
||||
@ -132,20 +170,20 @@ public class SendWarning {
|
||||
.append("<body>")
|
||||
.append("<div class='container'>")
|
||||
.append("<img src='https://ccalm.org/resources/images/locust.png' alt='Logo' class='logo'>") // Логотип
|
||||
.append("<h2>").append(trt.trt("Warning")).append("</h2>")
|
||||
.append("<p>").append(trt.trt("The_soil_temperature_has_exceeded_the_set_value")).append(": ").append(value).append("</p>")
|
||||
.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("Date")).append("</th><td>").append(tmp.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,"Date")).append("</th><td>").append(tmp_air.getString("date")).append("</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(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("</body>")
|
||||
.append("</html>");
|
||||
|
||||
boolean send = false;
|
||||
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,"Soil temperature"), html.toString());
|
||||
send = true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
@ -166,11 +204,74 @@ public class SendWarning {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(tmp_soil!=null) {
|
||||
Translation trt=new Translation(obj.getString("short_name"),jdbcTemplate);
|
||||
double value = obj.getDouble("value");
|
||||
if (value < tmp_soil.getDouble("value")) {
|
||||
String email = obj.getString("email");
|
||||
if(email.equals("irigm@mail.ru") || email.equals("ivanov.i@istt.kz")){ //TODO для тестирования потом удалить
|
||||
|
||||
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: 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; margin-top: 50px; }") // Отступ для логотипа
|
||||
.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("<img src='https://ccalm.org/resources/images/locust.png' alt='Logo' class='logo'>") // Логотип
|
||||
.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=true
|
||||
where uid=:uid
|
||||
""";
|
||||
MapSqlParameterSource param = new MapSqlParameterSource();
|
||||
param.addValue("uid", obj.getString("uid"), Types.INTEGER);
|
||||
int rowsUpdated = jdbcTemplate.update(sql, param);
|
||||
System.out.println("rowsUpdated = "+String.valueOf(rowsUpdated));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e);
|
||||
}
|
||||
return new ResponseEntity<>(result, HttpStatus.OK);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -23,7 +23,7 @@ public class SessionController {
|
||||
// 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
|
||||
public Object ajaxTest(@ModelAttribute User user) {
|
||||
|
||||
|
||||
@ -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", " ");
|
||||
}
|
||||
}
|
||||
23
src/main/java/org/ccalm/main/SpringContext.java
Normal file
23
src/main/java/org/ccalm/main/SpringContext.java
Normal 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;
|
||||
}
|
||||
}
|
||||
@ -33,7 +33,7 @@ public class TestFiles implements ServletContextAware {
|
||||
|
||||
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
|
||||
public Object ajaxTamer()
|
||||
{
|
||||
|
||||
@ -42,7 +42,7 @@ public class TranslationController implements ServletContextAware {
|
||||
/**
|
||||
* 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
|
||||
public String home(
|
||||
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
|
||||
public Map<String, String> getTranslations(
|
||||
@CookieValue(value = "lng", defaultValue = "1") String language_id
|
||||
) {
|
||||
|
||||
Map<String, String> translations = new HashMap<>();
|
||||
|
||||
try {
|
||||
|
||||
119
src/main/java/org/ccalm/main/api/APICountries.java
Normal file
119
src/main/java/org/ccalm/main/api/APICountries.java
Normal 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -5,10 +5,7 @@ import java.security.KeyFactory;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.sql.*;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
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.slf4j.Logger;
|
||||
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.core.io.ClassPathResource;
|
||||
@ -49,7 +47,7 @@ import tools.User;
|
||||
@Controller
|
||||
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 Properties m_props=null;
|
||||
//private String m_props_loc="";
|
||||
@ -73,7 +71,8 @@ public class EngineController implements ServletContextAware {
|
||||
PublicKey key = keyFactory.generatePublic(spec);
|
||||
return key;
|
||||
} catch (Exception e) {
|
||||
logger.error(e);
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -81,7 +80,7 @@ public class EngineController implements ServletContextAware {
|
||||
/**
|
||||
* 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(
|
||||
Model model,
|
||||
HttpServletResponse response,
|
||||
@ -89,10 +88,11 @@ public class EngineController implements ServletContextAware {
|
||||
@CookieValue(value = "lng", defaultValue = "1") int language_id
|
||||
) {
|
||||
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);
|
||||
return "redirect";
|
||||
}
|
||||
|
||||
//Проверяю подпись токена
|
||||
Jws<Claims> claims = null;
|
||||
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()
|
||||
.parseClaimsJws(jwt_a);
|
||||
} 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);
|
||||
model.addAttribute("url", redirectUrl);
|
||||
return "redirect";
|
||||
}
|
||||
//logger.warn("page engine is start");
|
||||
|
||||
//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);
|
||||
@ -125,7 +129,7 @@ public class EngineController implements ServletContextAware {
|
||||
}
|
||||
} catch( DataAccessException ex )
|
||||
{
|
||||
logger.info(ex.getMessage());
|
||||
logger.error(ex.getMessage());
|
||||
}
|
||||
|
||||
//Send user name and role
|
||||
|
||||
@ -1,72 +0,0 @@
|
||||
package org.ccalm.main.login;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jws;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import jakarta.servlet.ServletContext;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.ccalm.main.engine.EngineController;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.context.ServletContextAware;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import tctable.Tools;
|
||||
import tools.DBTools;
|
||||
import tools.User;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.security.PublicKey;
|
||||
import java.sql.*;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Controller
|
||||
public class LoginController implements ServletContextAware {
|
||||
|
||||
private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(EngineController.class);
|
||||
|
||||
private javax.servlet.ServletContext context;
|
||||
private final NamedParameterJdbcTemplate jdbcTemplate;
|
||||
|
||||
@Autowired
|
||||
public LoginController(NamedParameterJdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setServletContext(ServletContext servletContext) {
|
||||
this.context=context;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/login/login", method = RequestMethod.GET)
|
||||
public String home(
|
||||
@ModelAttribute User user,
|
||||
Model model,
|
||||
@CookieValue(value = "jwt_a", defaultValue = "") String jwt_a,
|
||||
@RequestParam(required=false,name="lng", defaultValue = "1") String language_id
|
||||
) {
|
||||
|
||||
String sql = "select identifier,translation from main._translations t where t.del=false and t.language_id=:language_id";
|
||||
try {
|
||||
MapSqlParameterSource parameters = new MapSqlParameterSource();
|
||||
parameters.addValue("language_id", Integer.valueOf(language_id));
|
||||
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
||||
for (int i = 0; i < ret.size(); i++) {
|
||||
JSONObject json = new JSONObject(ret.get(i));
|
||||
model.addAttribute(json.getString("identifier"), json.getString("identifier"));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid, ex);
|
||||
}
|
||||
|
||||
return "login/login";
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
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;
|
||||
|
||||
@ -13,6 +14,9 @@ import java.util.List;
|
||||
|
||||
public class ErrorResponseModel {
|
||||
|
||||
@JsonIgnore
|
||||
private int httpCode;
|
||||
|
||||
@Schema(description = "Error code", example = "10000")
|
||||
@JsonProperty("error_code")
|
||||
private int errorCode;
|
||||
@ -29,39 +33,46 @@ public class ErrorResponseModel {
|
||||
@JsonProperty("error_marker")
|
||||
private String errorMarker;
|
||||
|
||||
public ErrorResponseModel(int errorCode) {
|
||||
public ErrorResponseModel(int httpCode, int errorCode) {
|
||||
this.errorCode = errorCode;
|
||||
this.errorMessage = null;
|
||||
this.errorSetting = null;
|
||||
this.errorMarker = null;
|
||||
}
|
||||
|
||||
public ErrorResponseModel(int errorCode, List<String> errorMessage, String errorMarker) {
|
||||
public ErrorResponseModel(int httpCode, int errorCode, List<String> errorMessage, String errorMarker) {
|
||||
this.errorCode = errorCode;
|
||||
this.errorMessage = errorMessage;
|
||||
this.errorMarker = errorMarker;
|
||||
}
|
||||
|
||||
public ErrorResponseModel(int errorCode, String errorMessage, String 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 errorCode, String errorMessage, String errorSetting, String 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 errorCode, List<String> errorMessage, List<String> errorSetting, String 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;
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ 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;
|
||||
|
||||
@ -13,36 +14,40 @@ import java.util.List;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public class CustomException extends Exception {
|
||||
private static final Logger logger = LogManager.getLogger(CustomException.class);
|
||||
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CustomException.class);
|
||||
|
||||
private ErrorResponseModel error;
|
||||
@Getter
|
||||
private boolean saveToLog = false;
|
||||
|
||||
public CustomException(int errorCode, String errorMessage, String marker, boolean saveToLog) {
|
||||
public CustomException(int httpCode, int errorCode, String errorMessage, String marker, boolean saveToLog) {
|
||||
super(errorMessage);
|
||||
error = new ErrorResponseModel(errorCode, errorMessage, marker);
|
||||
error = new ErrorResponseModel(httpCode, errorCode, errorMessage, marker);
|
||||
this.saveToLog = saveToLog;
|
||||
}
|
||||
|
||||
public CustomException(int errorCode, String errorMessage, String errorSetting, String marker, boolean saveToLog) {
|
||||
public CustomException(int httpCode, int errorCode, String errorMessage, String errorSetting, String marker, boolean saveToLog) {
|
||||
super(errorMessage);
|
||||
error = new ErrorResponseModel(errorCode, errorMessage, errorSetting, marker);
|
||||
error = new ErrorResponseModel(httpCode, errorCode, errorMessage, errorSetting, marker);
|
||||
this.saveToLog = saveToLog;
|
||||
}
|
||||
|
||||
public CustomException(int errorCode, List<String> errorMessages, String marker, boolean saveToLog) {
|
||||
public CustomException(int httpCode, int errorCode, List<String> errorMessages, String marker, boolean saveToLog) {
|
||||
super(String.join(" ", errorMessages));
|
||||
error = new ErrorResponseModel(errorCode, errorMessages, marker);
|
||||
error = new ErrorResponseModel(httpCode, errorCode, errorMessages, marker);
|
||||
this.saveToLog = saveToLog;
|
||||
}
|
||||
|
||||
public CustomException(int errorCode, List<String> errorMessages, List<String> errorSettings, String marker, boolean saveToLog) {
|
||||
public CustomException(int httpCode, int errorCode, List<String> errorMessages, List<String> errorSettings, String marker, boolean saveToLog) {
|
||||
super(String.join(" ", errorMessages));
|
||||
error = new ErrorResponseModel(errorCode, errorMessages, errorSettings, marker);
|
||||
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();
|
||||
}
|
||||
|
||||
@ -4,8 +4,11 @@ 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;
|
||||
@ -14,12 +17,13 @@ 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 Tools {
|
||||
//---------------------------------------------------------------------------
|
||||
private static final Logger logger = LogManager.getLogger(Tools.class);
|
||||
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Tools.class);
|
||||
//---------------------------------------------------------------------------
|
||||
public static JSONObject createJSONError(int code, String message, String setting, String marker) {
|
||||
JSONObject json = new JSONObject();
|
||||
@ -29,7 +33,8 @@ public class Tools {
|
||||
json.put("error_setting", Arrays.asList(setting));
|
||||
json.put("error_marker", marker);
|
||||
} catch (JSONException e) {
|
||||
logger.error(e);
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
@ -32,7 +32,8 @@ public class Translation {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
public String trt(String text){
|
||||
public String trt(boolean translate,String text){
|
||||
if(translate) {
|
||||
String sql = """
|
||||
select
|
||||
translation
|
||||
@ -56,5 +57,8 @@ public class Translation {
|
||||
text = text.replace("_", " ");
|
||||
}
|
||||
return text;
|
||||
}else {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,13 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
|
||||
<conversionRule conversionWord="exOneLine" converterClass="org.ccalm.main.SingleLineThrowableProxyConverter"/>
|
||||
|
||||
<property name="LOGS" value="logs" />
|
||||
<springProperty scope="context" name="appName" source="spring.application.name"/>
|
||||
|
||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOGS}/${appName}.log</file>
|
||||
<encoder>
|
||||
<pattern>{"timestamp":"%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}","thread":"[%thread]","level":"%level","logger":"%logger{36}","message":"%msg"}%n</pattern>
|
||||
<pattern>{"timestamp":"%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}","thread":"[%thread]","level":"%level","logger":"%logger{36}","marker":"%marker","message":"%msg","exception":"%exOneLine"}%n</pattern>
|
||||
</encoder>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOGS}/${appName}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
|
||||
|
||||
@ -17,6 +17,7 @@
|
||||
|
||||
<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/sprintf.js"></script>
|
||||
<script type="text/javascript" src="../resources/metadata/qrcode.js"></script>
|
||||
@ -26,7 +27,7 @@
|
||||
<!--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 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"/>
|
||||
<script type="text/javascript" src="../resources/metadata/dbms/BrowserDetect.js?v=14"></script>
|
||||
<script type="text/javascript" src="../resources/metadata/dbms/tools.js?v=14"></script>
|
||||
@ -40,7 +41,7 @@
|
||||
|
||||
<script type="text/javascript" src="../resources/engine/popup.js?v=14"></script>
|
||||
<script type="text/javascript" src="../resources/engine/index.js?v=21"></script>
|
||||
<script type="text/javascript" src="../resources/engine/user.js?v=14"></script>
|
||||
<script type="text/javascript" src="../resources/engine/user.js?v=16"></script>
|
||||
|
||||
<style>
|
||||
html,
|
||||
@ -144,7 +145,7 @@ select{
|
||||
|
||||
</style>
|
||||
|
||||
<script>
|
||||
<script type="application/javascript">
|
||||
|
||||
if(window.location.host.indexOf('locust.kz')>=0){
|
||||
window.location.href = "https://ccalm.org";
|
||||
@ -354,6 +355,8 @@ function onLoadPage()
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
</script>
|
||||
</head>
|
||||
<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="padding-left:5px;" th:text="${Language}">Language</td>
|
||||
<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;">
|
||||
<option value="3">English</option>
|
||||
<option value="1">Russian Русский</option>
|
||||
@ -1412,8 +1416,6 @@ new Calendar({
|
||||
|
||||
<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>
|
||||
<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>
|
||||
@ -1654,6 +1656,9 @@ var vectorSourceV = new ol.source.Vector({});
|
||||
var vectorSourceDel = 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 vectorSourceCheckpoint = new ol.source.Vector({});
|
||||
@ -1758,6 +1763,14 @@ map = new ol.Map({
|
||||
new ol.layer.Vector({
|
||||
source: vectorSourceDelV,
|
||||
zIndex: 50
|
||||
}),
|
||||
new ol.layer.Vector({
|
||||
source: vectorSourceHealth,
|
||||
zIndex: 100
|
||||
}),
|
||||
new ol.layer.Vector({
|
||||
source: vectorSourceHealthV,
|
||||
zIndex: 50
|
||||
}),
|
||||
new ol.layer.Vector({
|
||||
source: vectorSourceArea,
|
||||
@ -1884,8 +1897,13 @@ map.on('singleclick', function(evt){ //map.on('click', function(evt){
|
||||
if(feature.userType=="FrmCheckpoint")
|
||||
{
|
||||
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 += '<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>';
|
||||
content.innerHTML =
|
||||
'<span style="white-space: nowrap;"><b>' + trt('Title') + '</b>: ' + feature.userTitle + '</span><br>' +
|
||||
'<span style="white-space: nowrap;"><b>' + trt('Creator') + '</b>: ' + feature.userName + '</span><br>' +
|
||||
'<span style="white-space: nowrap;"><b>' + trt('Radius') + '</b>: ' + feature.userRadius + 'm.</span><br>' +
|
||||
'<span style="white-space: nowrap;"><b>' + trt('Want_air_temperature') + '</b>: ' + feature.userTemperature_air + '°C</span><br>' +
|
||||
'<span style="white-space: nowrap;"><b>' + trt('Want_soil_temperature') + '</b>: ' + 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);
|
||||
}else{
|
||||
overlay.setPosition(undefined);
|
||||
@ -1994,7 +2012,6 @@ window.onresize = function()
|
||||
}
|
||||
onresize();
|
||||
|
||||
|
||||
onLoadPage();
|
||||
|
||||
</script>
|
||||
|
||||
@ -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>
|
||||
@ -8,7 +8,7 @@
|
||||
<meta name="yandex-verification" content="2cb5374be0668fe9" />
|
||||
<script type="text/javascript" src="./resources/metadata/jquery.js"></script>
|
||||
|
||||
<script type="text/javascript" src="./translation?v=7"></script>
|
||||
<script type="text/javascript" src="/api/translation/v01/array"></script>
|
||||
|
||||
<script src="./resources/metadata/dbms/tools.js?v=9"></script>
|
||||
<script src="./resources/metadata/dbms/window.js?v=10"></script>
|
||||
|
||||
Reference in New Issue
Block a user