From ed14a3fa9ec5b9ec11aa9424838d3870facd0dca Mon Sep 17 00:00:00 2001 From: igor Date: Tue, 24 Jun 2025 23:08:38 +0500 Subject: [PATCH] Preparing for the transition to REST API --- org-ccalm-main.yml | 3 +- pom.xml | 12 +- src/main/java/logging/Logger.java | 12 + src/main/java/logging/LoggerFactory.java | 22 + src/main/java/logging/SLF4JLogger.java | 18 + .../org/ccalm/main/AcceptASDCController.java | 18 +- src/main/java/org/ccalm/main/AcceptEXCEL.java | 2 +- src/main/java/org/ccalm/main/AcceptJSON.java | 43 +- src/main/java/org/ccalm/main/DataJSON.java | 2 +- .../java/org/ccalm/main/DownloadNDVI.java | 2 +- .../java/org/ccalm/main/DownloadWeather.java | 4 +- src/main/java/org/ccalm/main/GeoGSON.java | 4 +- .../ccalm/main/GlobalExceptionHandler.java | 48 + src/main/java/org/ccalm/main/Integration.java | 6 +- .../java/org/ccalm/main/MainController.java | 14 +- src/main/java/org/ccalm/main/Products.java | 1853 +++++++++-------- src/main/java/org/ccalm/main/QGIS.java | 2 +- src/main/java/org/ccalm/main/SendMail.java | 2 +- src/main/java/org/ccalm/main/SendWarning.java | 167 +- .../org/ccalm/main/SessionController.java | 2 +- .../SingleLineThrowableProxyConverter.java | 14 + .../java/org/ccalm/main/SpringContext.java | 23 + src/main/java/org/ccalm/main/TestFiles.java | 2 +- .../org/ccalm/main/TranslationController.java | 7 +- .../java/org/ccalm/main/api/APICountries.java | 119 ++ .../ccalm/main/engine/EngineController.java | 24 +- .../org/ccalm/main/login/LoginController.java | 72 - .../ccalm/main/models/ErrorResponseModel.java | 21 +- .../org/ccalm/main/utils/CustomException.java | 23 +- src/main/java/org/ccalm/main/utils/Tools.java | 9 +- src/main/java/tools/Translation.java | 50 +- src/main/resources/logback-spring.xml | 4 +- .../resources/templates/engine/index.html | 33 +- src/main/resources/templates/login/login.html | 391 ---- src/main/resources/templates/test.html | 2 +- 35 files changed, 1544 insertions(+), 1486 deletions(-) create mode 100644 src/main/java/logging/Logger.java create mode 100644 src/main/java/logging/LoggerFactory.java create mode 100644 src/main/java/logging/SLF4JLogger.java create mode 100644 src/main/java/org/ccalm/main/GlobalExceptionHandler.java create mode 100644 src/main/java/org/ccalm/main/SingleLineThrowableProxyConverter.java create mode 100644 src/main/java/org/ccalm/main/SpringContext.java create mode 100644 src/main/java/org/ccalm/main/api/APICountries.java delete mode 100644 src/main/java/org/ccalm/main/login/LoginController.java delete mode 100644 src/main/resources/templates/login/login.html diff --git a/org-ccalm-main.yml b/org-ccalm-main.yml index ead448d..f73da5a 100644 --- a/org-ccalm-main.yml +++ b/org-ccalm-main.yml @@ -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 diff --git a/pom.xml b/pom.xml index 9bb7cbb..d6e0b6d 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ org.ccalm main - 0.0.1-SNAPSHOT + 1.0.1 main main @@ -44,12 +44,12 @@ spring-boot-starter-test test - + org.springframework.boot spring-boot-starter-data-jdbc @@ -57,7 +57,7 @@ org.postgresql postgresql - 42.7.5 + 42.7.3 org.json @@ -143,10 +143,10 @@ 1.18.36 provided - + org-ccalm-main @@ -163,7 +163,7 @@ 2.22.2 - file:application.properties + file:org-ccalm-main.yml diff --git a/src/main/java/logging/Logger.java b/src/main/java/logging/Logger.java new file mode 100644 index 0000000..02de834 --- /dev/null +++ b/src/main/java/logging/Logger.java @@ -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); // Подменяется реализацией + } +} diff --git a/src/main/java/logging/LoggerFactory.java b/src/main/java/logging/LoggerFactory.java new file mode 100644 index 0000000..96922dc --- /dev/null +++ b/src/main/java/logging/LoggerFactory.java @@ -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; + } + } +} \ No newline at end of file diff --git a/src/main/java/logging/SLF4JLogger.java b/src/main/java/logging/SLF4JLogger.java new file mode 100644 index 0000000..5f70792 --- /dev/null +++ b/src/main/java/logging/SLF4JLogger.java @@ -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); } +} diff --git a/src/main/java/org/ccalm/main/AcceptASDCController.java b/src/main/java/org/ccalm/main/AcceptASDCController.java index 335f5b1..00757fc 100644 --- a/src/main/java/org/ccalm/main/AcceptASDCController.java +++ b/src/main/java/org/ccalm/main/AcceptASDCController.java @@ -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() { diff --git a/src/main/java/org/ccalm/main/AcceptEXCEL.java b/src/main/java/org/ccalm/main/AcceptEXCEL.java index ed6104d..3478285 100644 --- a/src/main/java/org/ccalm/main/AcceptEXCEL.java +++ b/src/main/java/org/ccalm/main/AcceptEXCEL.java @@ -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; diff --git a/src/main/java/org/ccalm/main/AcceptJSON.java b/src/main/java/org/ccalm/main/AcceptJSON.java index 1d217ce..e4c1270 100644 --- a/src/main/java/org/ccalm/main/AcceptJSON.java +++ b/src/main/java/org/ccalm/main/AcceptJSON.java @@ -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); diff --git a/src/main/java/org/ccalm/main/DataJSON.java b/src/main/java/org/ccalm/main/DataJSON.java index a0af76f..7a0a402 100644 --- a/src/main/java/org/ccalm/main/DataJSON.java +++ b/src/main/java/org/ccalm/main/DataJSON.java @@ -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) { diff --git a/src/main/java/org/ccalm/main/DownloadNDVI.java b/src/main/java/org/ccalm/main/DownloadNDVI.java index a0c8485..d1b63af 100644 --- a/src/main/java/org/ccalm/main/DownloadNDVI.java +++ b/src/main/java/org/ccalm/main/DownloadNDVI.java @@ -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) { diff --git a/src/main/java/org/ccalm/main/DownloadWeather.java b/src/main/java/org/ccalm/main/DownloadWeather.java index 729cf2d..872f18f 100644 --- a/src/main/java/org/ccalm/main/DownloadWeather.java +++ b/src/main/java/org/ccalm/main/DownloadWeather.java @@ -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; diff --git a/src/main/java/org/ccalm/main/GeoGSON.java b/src/main/java/org/ccalm/main/GeoGSON.java index acae0ba..fe6d4d9 100644 --- a/src/main/java/org/ccalm/main/GeoGSON.java +++ b/src/main/java/org/ccalm/main/GeoGSON.java @@ -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() { diff --git a/src/main/java/org/ccalm/main/GlobalExceptionHandler.java b/src/main/java/org/ccalm/main/GlobalExceptionHandler.java new file mode 100644 index 0000000..4503e56 --- /dev/null +++ b/src/main/java/org/ccalm/main/GlobalExceptionHandler.java @@ -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 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 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 handleError() { + ErrorResponseModel errorResponse = new ErrorResponseModel( + HttpStatus.NOT_FOUND.value(), + 10000, + "Unknown_error", + UUID.randomUUID().toString() + ); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } +} diff --git a/src/main/java/org/ccalm/main/Integration.java b/src/main/java/org/ccalm/main/Integration.java index ba10685..9d22059 100644 --- a/src/main/java/org/ccalm/main/Integration.java +++ b/src/main/java/org/ccalm/main/Integration.java @@ -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) { diff --git a/src/main/java/org/ccalm/main/MainController.java b/src/main/java/org/ccalm/main/MainController.java index ef74638..71c5fce 100644 --- a/src/main/java/org/ccalm/main/MainController.java +++ b/src/main/java/org/ccalm/main/MainController.java @@ -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("\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(); diff --git a/src/main/java/org/ccalm/main/Products.java b/src/main/java/org/ccalm/main/Products.java index a43e4f8..1e25062 100644 --- a/src/main/java/org/ccalm/main/Products.java +++ b/src/main/java/org/ccalm/main/Products.java @@ -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,932 +65,1039 @@ 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=""; - - Connection conn = null; - try { - Class.forName("org.postgresql.Driver"); - conn = DriverManager.getConnection(db_url, db_login, db_password); - if (conn != null) { - logger.info("Connect is OK!"); - } else { - errorCode=1; - errorMessage+="An error occurred while connecting to the database!"; - } - } catch (Exception ex) { - logger.info(ex.getMessage()); - errorCode=1; - errorMessage+="An error occurred while connecting to the database!"; - } - - try { - Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - //st.executeUpdate("SET TIME ZONE 'UTC';"); зачем коментил? - stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем раскоментил? может в начале поставить ещё TimeZone.setDefault(TimeZone.getTimeZone("UTC")); ? - stt0.close(); - } catch (SQLException ex) { - logger.info(ex.getMessage()); - errorCode=1; - errorMessage+="Failed to execute SQL query!"; - } - - JSONObject doc=null; - InputStream body; - if(reqData!=null) { - - - body = new ByteArrayInputStream(reqData); - - String text=""; - try { - text = new String(body.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - } - logger.info(text); - - //JSONParser jsonParser = new JSONParser(); - //doc = (JSONObject)jsonParser.parse(text); - //doc = new JSONObject(body); - doc = new JSONObject(text); - } - - JSONArray array=new JSONArray(); //Результирующий набор данных - - String sql_query = ""; - Statement stt=null; - ResultSet rs=null; - try { - stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - sql_query = "select id," - + " lat_center," - + " lon_center," - + " lat1," - + " lon1," - + " lat2," - + " lon2," - + " lat3," - + " lon3," - + " lat4," - + " lon4," - + " lat5," - + " lon5," - + " lat6," - + " lon6," - + " terrain," - + " locust_populated," - + " eggs_capsules_density," - + " eggs_capsules_density_to," - + " imago_density," - + " larva_density," - + " larva_density_to," - + " kuliguli_size," - + " CASE swarm_maturity WHEN true THEN 1 WHEN false THEN 0 ELSE null END as swarm_maturity," - + " swarm_density_id," - + " ST_AsGeoJSON(geom) as geom" - + " from main.frmlocust fl where" - + " fl.del=false" - + " and (${country_id} is null or (${country_id}=-1 and fl.country_id in (7,3,4,2)) or (${country_id}=-2 and fl.country_id in (7,1,5,6,8,9,10)) or ${country_id}=fl.country_id)" - + " and (${region_id} is null or ${region_id}=fl.region_id)" - + " and (${locust_type_id} is null or ${locust_type_id}=fl.locust_type_id)" - + " and (${date_start} is null or to_timestamp(${date_start})<=fl.date)" - + " and (${date_end} is null or to_timestamp(${date_end})>=fl.date)" - + " and (${device_id} is null or (${device_id} and fl.device_id is not null) or (not ${device_id} and fl.device_id is null))" - + " and (${registered} is null or (${registered} and (fl.device_id is null or fl.device_id in (select serial from main.terminals where del=false))) or (not ${registered} and (fl.device_id not in (select serial from main.terminals where del=false))))" - + " and ((${test} is null and (test!=true or test is null)) or ${test}=fl.test)" - + " order by fl.id desc;"; - - PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); - if(doc!=null) { - stmtn.setInt("_user_id", Integer.parseInt(user.id)); - - if(doc.isNull("country_id")) stmtn.setNULLInt("country_id"); - else stmtn.setInt("country_id",doc.getInt("country_id")); - - if(doc.isNull("region_id")) stmtn.setNULLInt("region_id"); - else stmtn.setInt("region_id",doc.getInt("region_id")); - - if(doc.isNull("locust_type_id")) stmtn.setNULLInt("locust_type_id"); - else stmtn.setInt("locust_type_id",doc.getInt("locust_type_id")); - - if(doc.isNull("date_start")) stmtn.setNULLInt("date_start"); - else stmtn.setInt("date_start",doc.getInt("date_start")); - - if(doc.isNull("date_end")) stmtn.setNULLInt("date_end"); - else stmtn.setInt("date_end",doc.getInt("date_end")); - - if(doc.isNull("device_id")) stmtn.setNULLBoolean("device_id"); - else stmtn.setBoolean("device_id",doc.getInt("device_id")); - - if(doc.isNull("registered")) stmtn.setNULLBoolean("registered"); - else stmtn.setBoolean("registered",doc.getInt("registered")); - - if(doc.isNull("test")) stmtn.setNULLBoolean("test"); - else stmtn.setBoolean("test",doc.getInt("test")); - } - PreparedStatement stmt=stmtn.getPreparedStatement(); - - rs = stmt.executeQuery(); - if (rs != null) { - try { - while(rs.next()) { - - JSONObject obj = new JSONObject(); - obj.put("id", rs.getLong("id")); - if(rs.getObject("terrain")!=null) - obj.put("terrain", rs.getString("terrain")); - if(rs.getObject("locust_populated")!=null) - obj.put("locust_populated", rs.getFloat("locust_populated")); - if(rs.getObject("eggs_capsules_density")!=null) - obj.put("eggs_capsules_density", rs.getFloat("eggs_capsules_density")); - if(rs.getObject("eggs_capsules_density_to")!=null) - obj.put("eggs_capsules_density_to", rs.getFloat("eggs_capsules_density_to")); - if(rs.getObject("imago_density")!=null) - obj.put("imago_density", rs.getFloat("imago_density")); - if(rs.getObject("larva_density")!=null) - obj.put("larva_density", rs.getFloat("larva_density")); - if(rs.getObject("larva_density_to")!=null) - obj.put("larva_density_to", rs.getFloat("larva_density_to")); - if(rs.getObject("kuliguli_size")!=null) - obj.put("kuliguli_size", rs.getFloat("kuliguli_size")); - if(rs.getObject("swarm_maturity")!=null) - obj.put("swarm_maturity", rs.getString("swarm_maturity")); - if(rs.getObject("swarm_density_id")!=null) - obj.put("swarm_density_id", rs.getInt("swarm_density_id")); - - //obj.put("town_name", rs.getString("town_name")); //Район - //obj.put("date", rs.getString("date")); //Дата анкетирования - //obj.put("surveyed_area", rs.getDouble("surveyed_area")); //Обследованная площадь га - - - double lat=0; - double lon=0; - int cnt1=0; - if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { - lat+=rs.getDouble("lat1"); - lon+=rs.getDouble("lon1"); - cnt1++; - } - if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { - lat+=rs.getDouble("lat2"); - lon+=rs.getDouble("lon2"); - cnt1++; - } - if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { - lat+=rs.getDouble("lat3"); - lon+=rs.getDouble("lon3"); - cnt1++; - } - if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { - lat+=rs.getDouble("lat4"); - lon+=rs.getDouble("lon4"); - cnt1++; - } - if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { - lat+=rs.getDouble("lat5"); - lon+=rs.getDouble("lon5"); - cnt1++; - } - if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { - lat+=rs.getDouble("lat6"); - lon+=rs.getDouble("lon6"); - cnt1++; - } - if(cnt1>0) { - lat=lat/cnt1; - lon=lon/cnt1; - }else{ - if(rs.getString("lat_center")!=null && rs.getString("lon_center")!=null && rs.getFloat("lat_center")!=0 && rs.getFloat("lon_center")!=0) { - lat=rs.getDouble("lat_center"); - lon=rs.getDouble("lon_center"); - } - } - obj.put("lat", lat); - obj.put("lon", lon); - boolean point=cnt1<=2; - - JSONObject geom = null; - if(rs.getString("geom")!=null) - { - try { - geom = new JSONObject(rs.getString("geom")); - }catch (JSONException err){ - - } - }else { - if(point) { - /*geom = new JSONObject(); - geom.put("type","Point"); - JSONArray crdSub=new JSONArray(); - crdSub.put(rs.getDouble("lon1")); - crdSub.put(rs.getDouble("lat1")); - geom.put("coordinates", crdSub);*/ - }else { - geom = new JSONObject(); - geom.put("type","Polygon"); - JSONArray crdMain=new JSONArray(); - JSONArray crdSub=new JSONArray(); - crdMain.put(crdSub); - - if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon1")); - crd.put(rs.getDouble("lat1")); - crdSub.put(crd); - } - if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon2")); - crd.put(rs.getDouble("lat2")); - crdSub.put(crd); - } - if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon3")); - crd.put(rs.getDouble("lat3")); - crdSub.put(crd); - } - if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon4")); - crd.put(rs.getDouble("lat4")); - crdSub.put(crd); - } - if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon5")); - crd.put(rs.getDouble("lat5")); - crdSub.put(crd); - } - if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon6")); - crd.put(rs.getDouble("lat6")); - crdSub.put(crd); - } - geom.put("coordinates", crdMain); - } - } - - if(geom!=null) - obj.put("geom", geom); - - array.put(obj); - } - rs.close(); - } catch (SQLException ex) { - errorCode=4; - errorMessage+="Internal server error, sampling."; - ex.printStackTrace(); - logger.info(ex.getMessage()); + public ResponseEntity 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 = 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 { + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + if (conn != null) { + logger.info("Connect is OK!"); + } else { + throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true); + } + } catch (Exception ex) { + throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true); + } + + try { + Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + //st.executeUpdate("SET TIME ZONE 'UTC';"); зачем коментил? + stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем раскоментил? может в начале поставить ещё TimeZone.setDefault(TimeZone.getTimeZone("UTC")); ? + stt0.close(); + } catch (SQLException ex) { + throw new CustomException(200, 10000, trt.trt(false, "Failed to execute SQL query!"), UUID.randomUUID().toString(),true); + } + + JSONObject doc=null; + InputStream body; + if(reqData!=null) { + + + body = new ByteArrayInputStream(reqData); + + String text=""; + try { + text = new String(body.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + logger.info(text); + + //JSONParser jsonParser = new JSONParser(); + //doc = (JSONObject)jsonParser.parse(text); + //doc = new JSONObject(body); + doc = new JSONObject(text); + } + + JSONArray array=new JSONArray(); //Результирующий набор данных + + String sql_query = ""; + Statement stt=null; + ResultSet rs=null; + try { + stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + sql_query = "select id," + + " lat_center," + + " lon_center," + + " lat1," + + " lon1," + + " lat2," + + " lon2," + + " lat3," + + " lon3," + + " lat4," + + " lon4," + + " lat5," + + " lon5," + + " lat6," + + " lon6," + + " terrain," + + " locust_populated," + + " eggs_capsules_density," + + " eggs_capsules_density_to," + + " imago_density," + + " larva_density," + + " larva_density_to," + + " kuliguli_size," + + " CASE swarm_maturity WHEN true THEN 1 WHEN false THEN 0 ELSE null END as swarm_maturity," + + " swarm_density_id," + + " ST_AsGeoJSON(geom) as geom" + + " from main.frmlocust fl where" + + " fl.del=false" + + " and (${country_id} is null or (${country_id}=-1 and fl.country_id in (7,3,4,2)) or (${country_id}=-2 and fl.country_id in (7,1,5,6,8,9,10)) or ${country_id}=fl.country_id)" + + " and (${region_id} is null or ${region_id}=fl.region_id)" + + " and (${locust_type_id} is null or ${locust_type_id}=fl.locust_type_id)" + + " and (${date_start} is null or to_timestamp(${date_start})<=fl.date)" + + " and (${date_end} is null or to_timestamp(${date_end})>=fl.date)" + + " and (${device_id} is null or (${device_id} and fl.device_id is not null) or (not ${device_id} and fl.device_id is null))" + + " and (${registered} is null or (${registered} and (fl.device_id is null or fl.device_id in (select serial from main.terminals where del=false))) or (not ${registered} and (fl.device_id not in (select serial from main.terminals where del=false))))" + + " and ((${test} is null and (test!=true or test is null)) or ${test}=fl.test)" + + " order by fl.id desc;"; + + PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); + if(doc!=null) { + stmtn.setInt("_user_id", Integer.parseInt(user.id)); + + if(doc.isNull("country_id")) stmtn.setNULLInt("country_id"); + else stmtn.setInt("country_id",doc.getInt("country_id")); + + if(doc.isNull("region_id")) stmtn.setNULLInt("region_id"); + else stmtn.setInt("region_id",doc.getInt("region_id")); + + if(doc.isNull("locust_type_id")) stmtn.setNULLInt("locust_type_id"); + else stmtn.setInt("locust_type_id",doc.getInt("locust_type_id")); + + if(doc.isNull("date_start")) stmtn.setNULLInt("date_start"); + else stmtn.setInt("date_start",doc.getInt("date_start")); + + if(doc.isNull("date_end")) stmtn.setNULLInt("date_end"); + else stmtn.setInt("date_end",doc.getInt("date_end")); + + if(doc.isNull("device_id")) stmtn.setNULLBoolean("device_id"); + else stmtn.setBoolean("device_id",doc.getInt("device_id")); + + if(doc.isNull("registered")) stmtn.setNULLBoolean("registered"); + else stmtn.setBoolean("registered",doc.getInt("registered")); + + if(doc.isNull("test")) stmtn.setNULLBoolean("test"); + else stmtn.setBoolean("test",doc.getInt("test")); + } + PreparedStatement stmt=stmtn.getPreparedStatement(); + + rs = stmt.executeQuery(); + if (rs != null) { + try { + while(rs.next()) { + + JSONObject obj = new JSONObject(); + obj.put("id", rs.getLong("id")); + if(rs.getObject("terrain")!=null) + obj.put("terrain", rs.getString("terrain")); + if(rs.getObject("locust_populated")!=null) + obj.put("locust_populated", rs.getFloat("locust_populated")); + if(rs.getObject("eggs_capsules_density")!=null) + obj.put("eggs_capsules_density", rs.getFloat("eggs_capsules_density")); + if(rs.getObject("eggs_capsules_density_to")!=null) + obj.put("eggs_capsules_density_to", rs.getFloat("eggs_capsules_density_to")); + if(rs.getObject("imago_density")!=null) + obj.put("imago_density", rs.getFloat("imago_density")); + if(rs.getObject("larva_density")!=null) + obj.put("larva_density", rs.getFloat("larva_density")); + if(rs.getObject("larva_density_to")!=null) + obj.put("larva_density_to", rs.getFloat("larva_density_to")); + if(rs.getObject("kuliguli_size")!=null) + obj.put("kuliguli_size", rs.getFloat("kuliguli_size")); + if(rs.getObject("swarm_maturity")!=null) + obj.put("swarm_maturity", rs.getString("swarm_maturity")); + if(rs.getObject("swarm_density_id")!=null) + obj.put("swarm_density_id", rs.getInt("swarm_density_id")); + + //obj.put("town_name", rs.getString("town_name")); //Район + //obj.put("date", rs.getString("date")); //Дата анкетирования + //obj.put("surveyed_area", rs.getDouble("surveyed_area")); //Обследованная площадь га + + + double lat=0; + double lon=0; + int cnt1=0; + if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { + lat+=rs.getDouble("lat1"); + lon+=rs.getDouble("lon1"); + cnt1++; + } + if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { + lat+=rs.getDouble("lat2"); + lon+=rs.getDouble("lon2"); + cnt1++; + } + if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { + lat+=rs.getDouble("lat3"); + lon+=rs.getDouble("lon3"); + cnt1++; + } + if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { + lat+=rs.getDouble("lat4"); + lon+=rs.getDouble("lon4"); + cnt1++; + } + if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { + lat+=rs.getDouble("lat5"); + lon+=rs.getDouble("lon5"); + cnt1++; + } + if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { + lat+=rs.getDouble("lat6"); + lon+=rs.getDouble("lon6"); + cnt1++; + } + if(cnt1>0) { + lat=lat/cnt1; + lon=lon/cnt1; + }else{ + if(rs.getString("lat_center")!=null && rs.getString("lon_center")!=null && rs.getFloat("lat_center")!=0 && rs.getFloat("lon_center")!=0) { + lat=rs.getDouble("lat_center"); + lon=rs.getDouble("lon_center"); + } + } + obj.put("lat", lat); + obj.put("lon", lon); + boolean point=cnt1<=2; + + JSONObject geom = null; + if(rs.getString("geom")!=null) + { + try { + geom = new JSONObject(rs.getString("geom")); + }catch (JSONException err){ + + } + }else { + if(point) { + /*geom = new JSONObject(); + geom.put("type","Point"); + JSONArray crdSub=new JSONArray(); + crdSub.put(rs.getDouble("lon1")); + crdSub.put(rs.getDouble("lat1")); + geom.put("coordinates", crdSub);*/ + }else { + geom = new JSONObject(); + geom.put("type","Polygon"); + JSONArray crdMain=new JSONArray(); + JSONArray crdSub=new JSONArray(); + crdMain.put(crdSub); + + if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon1")); + crd.put(rs.getDouble("lat1")); + crdSub.put(crd); + } + if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon2")); + crd.put(rs.getDouble("lat2")); + crdSub.put(crd); + } + if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon3")); + crd.put(rs.getDouble("lat3")); + crdSub.put(crd); + } + if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon4")); + crd.put(rs.getDouble("lat4")); + crdSub.put(crd); + } + if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon5")); + crd.put(rs.getDouble("lat5")); + crdSub.put(crd); + } + if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon6")); + crd.put(rs.getDouble("lat6")); + crdSub.put(crd); + } + geom.put("coordinates", crdMain); + } + } + + if(geom!=null) + obj.put("geom", geom); + + array.put(obj); + } + rs.close(); + } catch (SQLException ex) { + 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) { + 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){} } - } catch (SQLException ex) { - errorCode=5; - errorMessage+="Внутренняя ошибка сервера, запрос. "; - ex.printStackTrace(); - logger.info(ex.getMessage()); - }finally { - if(rs!=null) try{rs.close();}catch(SQLException ex){} - if(stt!=null) try{stt.close();}catch(SQLException ex){} - } - - if(errorCode!=0) { - JSONObject obj = new JSONObject(); - obj.put("error_code",errorCode); - obj.put("error_message", errorMessage); - return obj.toString(); - }else { JSONObject obj = new JSONObject(); obj.put("error_code",0); obj.put("error_message", ""); if(doc!=null) obj.put("indicator",doc.getString("indicator")); obj.put("data",array); - return obj.toString(); - } + 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=""; - - Connection conn = null; - try { - Class.forName("org.postgresql.Driver"); - conn = DriverManager.getConnection(db_url, db_login, db_password); - if (conn != null) { - logger.info("Connect is OK!"); - } else { - errorCode=1; - errorMessage+="An error occurred while connecting to the database!"; - } - } catch (Exception ex) { - logger.info(ex.getMessage()); - errorCode=1; - errorMessage+="An error occurred while connecting to the database!"; - } - - try { - Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - //st.executeUpdate("SET TIME ZONE 'UTC';"); зачем коментил? - stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); - stt0.close(); - } catch (SQLException ex) { - logger.info(ex.getMessage()); - errorCode=1; - errorMessage+="Failed to execute SQL query!"; - } - - JSONObject doc=null; - InputStream body; - if(reqData!=null) { - - - body = new ByteArrayInputStream(reqData); - - String text=""; - try { - text = new String(body.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - } - logger.info(text); - - //JSONParser jsonParser = new JSONParser(); - //doc = (JSONObject)jsonParser.parse(text); - //doc = new JSONObject(body); - doc = new JSONObject(text); - } - - JSONArray array=new JSONArray(); //Результирующий набор данных - - String sql_query = ""; - Statement stt=null; - ResultSet rs=null; - try { - stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - sql_query = "select id," - + " lat_center," - + " lon_center," - + " lat1," - + " lon1," - + " lat2," - + " lon2," - + " lat3," - + " lon3," - + " lat4," - + " lon4," - + " lat5," - + " lon5," - + " lat6," - + " lon6," - + " terrain," - + " treated_area," - + " infested_area," - + " ST_AsGeoJSON(geom) as geom" - + " from main.frmlocustdel fld where" - + " fld.del=false" - + " and (${country_id} is null or (${country_id}=-1 and fld.country_id in (7,3,4,2)) or (${country_id}=-2 and fld.country_id in (7,1,5,6,8,9,10)) or ${country_id}=fld.country_id)" - + " and (${region_id} is null or ${region_id}=fld.region_id)" - + " and (${date_start} is null or to_timestamp(${date_start})<=fld.date)" - + " and (${date_end} is null or to_timestamp(${date_end})>=fld.date)" - + " and (${device_id} is null or (${device_id} and fld.device_id is not null) or (not ${device_id} and fld.device_id is null))" - + " and (${registered} is null or (${registered} and (fld.device_id is null or fld.device_id in (select serial from main.terminals where del=false))) or (not ${registered} and (fld.device_id not in (select serial from main.terminals where del=false))))" - + " and ((${test} is null and (test!=true or test is null)) or ${test}=fld.test)" - + " order by fld.id desc;"; - - PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); - if(doc!=null) { - stmtn.setInt("_user_id", Integer.parseInt(user.id)); - - if(doc.isNull("country_id")) stmtn.setNULLInt("country_id"); - else stmtn.setInt("country_id",doc.getInt("country_id")); - - if(doc.isNull("region_id")) stmtn.setNULLInt("region_id"); - else stmtn.setInt("region_id",doc.getInt("region_id")); - - if(doc.isNull("locust_type_id")) stmtn.setNULLInt("locust_type_id"); - else stmtn.setInt("locust_type_id",doc.getInt("locust_type_id")); - - if(doc.isNull("date_start")) stmtn.setNULLInt("date_start"); - else stmtn.setInt("date_start",doc.getInt("date_start")); - - if(doc.isNull("date_end")) stmtn.setNULLInt("date_end"); - else stmtn.setInt("date_end",doc.getInt("date_end")); - - if(doc.isNull("device_id")) stmtn.setNULLBoolean("device_id"); - else stmtn.setBoolean("device_id",doc.getInt("device_id")); - - if(doc.isNull("registered")) stmtn.setNULLBoolean("registered"); - else stmtn.setBoolean("registered",doc.getInt("registered")); - - if(doc.isNull("test")) stmtn.setNULLBoolean("test"); - else stmtn.setBoolean("test",doc.getInt("test")); - } - PreparedStatement stmt=stmtn.getPreparedStatement(); - - rs = stmt.executeQuery(); - if (rs != null) { + public ResponseEntity 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 = null; + PublicKey key_a = getPublicKey(); try { - while(rs.next()) { + 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(); + } - JSONObject obj = new JSONObject(); - obj.put("id", rs.getLong("id")); - if(rs.getObject("terrain")!=null) - obj.put("terrain", rs.getString("terrain")); - if(rs.getObject("treated_area")!=null) - obj.put("treated_area", rs.getFloat("treated_area")); - if(rs.getObject("infested_area")!=null) - obj.put("infested_area", rs.getFloat("infested_area")); + 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 { + throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true); + } + } catch (Exception ex) { + throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true); + } - double lat=0; - double lon=0; - int cnt1=0; - if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { - lat+=rs.getDouble("lat1"); - lon+=rs.getDouble("lon1"); - cnt1++; - } - if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { - lat+=rs.getDouble("lat2"); - lon+=rs.getDouble("lon2"); - cnt1++; - } - if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { - lat+=rs.getDouble("lat3"); - lon+=rs.getDouble("lon3"); - cnt1++; - } - if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { - lat+=rs.getDouble("lat4"); - lon+=rs.getDouble("lon4"); - cnt1++; - } - if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { - lat+=rs.getDouble("lat5"); - lon+=rs.getDouble("lon5"); - cnt1++; - } - if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { - lat+=rs.getDouble("lat6"); - lon+=rs.getDouble("lon6"); - cnt1++; - } - //lat=lat/cnt1; - //lon=lon/cnt1; - lat=rs.getDouble("lat_center"); - lon=rs.getDouble("lon_center"); - obj.put("lat", lat); - obj.put("lon", lon); - boolean point=cnt1<=2; + try { + Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + //st.executeUpdate("SET TIME ZONE 'UTC';"); зачем коментил? + stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); + stt0.close(); + } catch (SQLException ex) { + throw new CustomException(200, 10000, trt.trt(false, "Failed to execute SQL query!"), UUID.randomUUID().toString(),true); + } - JSONObject geom = null; + JSONObject doc=null; + InputStream body; + if(reqData!=null) { - if(rs.getString("geom")!=null) - { - try { - geom = new JSONObject(rs.getString("geom")); - }catch (JSONException err){ + body = new ByteArrayInputStream(reqData); + + String text=""; + try { + text = new String(body.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + logger.info(text); + + //JSONParser jsonParser = new JSONParser(); + //doc = (JSONObject)jsonParser.parse(text); + //doc = new JSONObject(body); + doc = new JSONObject(text); + } + + JSONArray array=new JSONArray(); //Результирующий набор данных + + String sql_query = ""; + Statement stt=null; + ResultSet rs=null; + try { + stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + sql_query = "select id," + + " lat_center," + + " lon_center," + + " lat1," + + " lon1," + + " lat2," + + " lon2," + + " lat3," + + " lon3," + + " lat4," + + " lon4," + + " lat5," + + " lon5," + + " lat6," + + " lon6," + + " terrain," + + " treated_area," + + " infested_area," + + " ST_AsGeoJSON(geom) as geom" + + " from main.frmlocustdel fld where" + + " fld.del=false" + + " and (${country_id} is null or (${country_id}=-1 and fld.country_id in (7,3,4,2)) or (${country_id}=-2 and fld.country_id in (7,1,5,6,8,9,10)) or ${country_id}=fld.country_id)" + + " and (${region_id} is null or ${region_id}=fld.region_id)" + + " and (${date_start} is null or to_timestamp(${date_start})<=fld.date)" + + " and (${date_end} is null or to_timestamp(${date_end})>=fld.date)" + + " and (${device_id} is null or (${device_id} and fld.device_id is not null) or (not ${device_id} and fld.device_id is null))" + + " and (${registered} is null or (${registered} and (fld.device_id is null or fld.device_id in (select serial from main.terminals where del=false))) or (not ${registered} and (fld.device_id not in (select serial from main.terminals where del=false))))" + + " and ((${test} is null and (test!=true or test is null)) or ${test}=fld.test)" + + " order by fld.id desc;"; + + PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); + if(doc!=null) { + stmtn.setInt("_user_id", Integer.parseInt(user.id)); + + if(doc.isNull("country_id")) stmtn.setNULLInt("country_id"); + else stmtn.setInt("country_id",doc.getInt("country_id")); + + if(doc.isNull("region_id")) stmtn.setNULLInt("region_id"); + else stmtn.setInt("region_id",doc.getInt("region_id")); + + if(doc.isNull("locust_type_id")) stmtn.setNULLInt("locust_type_id"); + else stmtn.setInt("locust_type_id",doc.getInt("locust_type_id")); + + if(doc.isNull("date_start")) stmtn.setNULLInt("date_start"); + else stmtn.setInt("date_start",doc.getInt("date_start")); + + if(doc.isNull("date_end")) stmtn.setNULLInt("date_end"); + else stmtn.setInt("date_end",doc.getInt("date_end")); + + if(doc.isNull("device_id")) stmtn.setNULLBoolean("device_id"); + else stmtn.setBoolean("device_id",doc.getInt("device_id")); + + if(doc.isNull("registered")) stmtn.setNULLBoolean("registered"); + else stmtn.setBoolean("registered",doc.getInt("registered")); + + if(doc.isNull("test")) stmtn.setNULLBoolean("test"); + else stmtn.setBoolean("test",doc.getInt("test")); + } + PreparedStatement stmt=stmtn.getPreparedStatement(); + + rs = stmt.executeQuery(); + if (rs != null) { + try { + while(rs.next()) { + + JSONObject obj = new JSONObject(); + obj.put("id", rs.getLong("id")); + if(rs.getObject("terrain")!=null) + obj.put("terrain", rs.getString("terrain")); + if(rs.getObject("treated_area")!=null) + obj.put("treated_area", rs.getFloat("treated_area")); + if(rs.getObject("infested_area")!=null) + obj.put("infested_area", rs.getFloat("infested_area")); + + double lat=0; + double lon=0; + int cnt1=0; + if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { + lat+=rs.getDouble("lat1"); + lon+=rs.getDouble("lon1"); + cnt1++; } - }else { - if(point) { - /*geom = new JSONObject(); - geom.put("type","Point"); - JSONArray crdSub=new JSONArray(); - crdSub.put(rs.getDouble("lon1")); - crdSub.put(rs.getDouble("lat1")); - geom.put("coordinates", crdSub);*/ + if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { + lat+=rs.getDouble("lat2"); + lon+=rs.getDouble("lon2"); + cnt1++; + } + if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { + lat+=rs.getDouble("lat3"); + lon+=rs.getDouble("lon3"); + cnt1++; + } + if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { + lat+=rs.getDouble("lat4"); + lon+=rs.getDouble("lon4"); + cnt1++; + } + if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { + lat+=rs.getDouble("lat5"); + lon+=rs.getDouble("lon5"); + cnt1++; + } + if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { + lat+=rs.getDouble("lat6"); + lon+=rs.getDouble("lon6"); + cnt1++; + } + //lat=lat/cnt1; + //lon=lon/cnt1; + lat=rs.getDouble("lat_center"); + lon=rs.getDouble("lon_center"); + obj.put("lat", lat); + obj.put("lon", lon); + boolean point=cnt1<=2; + + JSONObject geom = null; + + if(rs.getString("geom")!=null) + { + try { + geom = new JSONObject(rs.getString("geom")); + }catch (JSONException err){ + + } }else { - geom = new JSONObject(); - geom.put("type","Polygon"); - JSONArray crdMain=new JSONArray(); - JSONArray crdSub=new JSONArray(); - crdMain.put(crdSub); - - if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon1")); - crd.put(rs.getDouble("lat1")); - crdSub.put(crd); + if(point) { + /*geom = new JSONObject(); + geom.put("type","Point"); + JSONArray crdSub=new JSONArray(); + crdSub.put(rs.getDouble("lon1")); + crdSub.put(rs.getDouble("lat1")); + geom.put("coordinates", crdSub);*/ + }else { + geom = new JSONObject(); + geom.put("type","Polygon"); + JSONArray crdMain=new JSONArray(); + JSONArray crdSub=new JSONArray(); + crdMain.put(crdSub); + + if(rs.getString("lat1")!=null && rs.getString("lon1")!=null && rs.getFloat("lat1")!=0 && rs.getFloat("lon1")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon1")); + crd.put(rs.getDouble("lat1")); + crdSub.put(crd); + } + if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon2")); + crd.put(rs.getDouble("lat2")); + crdSub.put(crd); + } + if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon3")); + crd.put(rs.getDouble("lat3")); + crdSub.put(crd); + } + if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon4")); + crd.put(rs.getDouble("lat4")); + crdSub.put(crd); + } + if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon5")); + crd.put(rs.getDouble("lat5")); + crdSub.put(crd); + } + if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { + JSONArray crd=new JSONArray(); + crd.put(rs.getDouble("lon6")); + crd.put(rs.getDouble("lat6")); + crdSub.put(crd); + } + geom.put("coordinates", crdMain); } - if(rs.getString("lat2")!=null && rs.getString("lon2")!=null && rs.getFloat("lat2")!=0 && rs.getFloat("lon2")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon2")); - crd.put(rs.getDouble("lat2")); - crdSub.put(crd); - } - if(rs.getString("lat3")!=null && rs.getString("lon3")!=null && rs.getFloat("lat3")!=0 && rs.getFloat("lon3")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon3")); - crd.put(rs.getDouble("lat3")); - crdSub.put(crd); - } - if(rs.getString("lat4")!=null && rs.getString("lon4")!=null && rs.getFloat("lat4")!=0 && rs.getFloat("lon4")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon4")); - crd.put(rs.getDouble("lat4")); - crdSub.put(crd); - } - if(rs.getString("lat5")!=null && rs.getString("lon5")!=null && rs.getFloat("lat5")!=0 && rs.getFloat("lon5")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon5")); - crd.put(rs.getDouble("lat5")); - crdSub.put(crd); - } - if(rs.getString("lat6")!=null && rs.getString("lon6")!=null && rs.getFloat("lat6")!=0 && rs.getFloat("lon6")!=0) { - JSONArray crd=new JSONArray(); - crd.put(rs.getDouble("lon6")); - crd.put(rs.getDouble("lat6")); - crdSub.put(crd); - } - geom.put("coordinates", crdMain); } + if(geom!=null) + obj.put("geom", geom); + + array.put(obj); } - if(geom!=null) - obj.put("geom", geom); - - array.put(obj); + rs.close(); + } catch (SQLException ex) { + 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); } - rs.close(); - } catch (SQLException ex) { - errorCode=4; - errorMessage+="Internal server error, sampling."; - ex.printStackTrace(); - logger.info(ex.getMessage()); } + } catch (SQLException ex) { + 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){} } - } catch (SQLException ex) { - errorCode=5; - errorMessage+="Внутренняя ошибка сервера, запрос. "; - ex.printStackTrace(); - logger.info(ex.getMessage()); - }finally { - if(rs!=null) try{rs.close();}catch(SQLException ex){} - if(stt!=null) try{stt.close();}catch(SQLException ex){} - } - - if(errorCode!=0) { - JSONObject obj = new JSONObject(); - obj.put("error_code",errorCode); - obj.put("error_message", errorMessage); - return obj.toString(); - }else { JSONObject obj = new JSONObject(); obj.put("error_code",0); obj.put("error_message", ""); obj.put("data",array); - return obj.toString(); + 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") - @ResponseBody - public String getCheckpoints(@ModelAttribute User user,@RequestBody byte[] reqData,@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); - //st.executeUpdate("SET TIME ZONE 'UTC';"); зачем коментил? - stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); - stt0.close(); - } catch (SQLException ex) { - logger.info(ex.getMessage()); - errorCode=1; - errorMessage+="Failed to execute SQL query!"; - } - - JSONObject doc=null; - InputStream body; - if(reqData!=null) { - - - body = new ByteArrayInputStream(reqData); - - String text=""; - try { - text = new String(body.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - } - logger.info(text); - - //JSONParser jsonParser = new JSONParser(); - //doc = (JSONObject)jsonParser.parse(text); - //doc = new JSONObject(body); - doc = new JSONObject(text); - } - - JSONArray array=new JSONArray(); //Результирующий набор данных - - String sql_query = ""; - Statement stt=null; - ResultSet rs=null; - try { - stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - sql_query = """ - select - f.id, - f.country_id, - u.name as user_name, - f.lat, - f.lon, - f.radius, - f.name, - f.temperature - from - main.frmcheckpoints f - left join main._users u on u.id=f.user_id - where - f.del=false - and (${country_id} is null or (${country_id}=-1 and f.country_id in (7,3,4,2)) or (${country_id}=-2 and f.country_id in (7,1,5,6,8,9,10)) or ${country_id}=f.country_id) - order by f.id desc;"""; - - PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); - if(doc!=null) { - //stmtn.setInt("_user_id", Integer.parseInt(user.id)); - - if(doc.isNull("country_id")) stmtn.setNULLInt("country_id"); - else stmtn.setInt("country_id",doc.getInt("country_id")); - } - PreparedStatement stmt=stmtn.getPreparedStatement(); - - rs = stmt.executeQuery(); - if (rs != null) { - try { - while(rs.next()) { - - JSONObject obj = new JSONObject(); - obj.put("id", rs.getLong("id")); - - double lat=0; - double lon=0; - lat=rs.getDouble("lat"); - lon=rs.getDouble("lon"); - obj.put("user_name", rs.getString("user_name")); - obj.put("name", rs.getString("name")); - obj.put("lat", lat); - obj.put("lon", lon); - obj.put("radius", rs.getFloat("radius")); - obj.put("temperature", rs.getFloat("temperature")); - array.put(obj); - } - rs.close(); - } catch (SQLException ex) { - errorCode=4; - errorMessage+="Internal server error, sampling."; - ex.printStackTrace(); - logger.info(ex.getMessage()); + @RequestMapping(value = { "/api/locust/v01/get_health"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8") + @ResponseBody + public ResponseEntity 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 = 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(); } - } catch (SQLException ex) { - errorCode=5; - errorMessage+="Internal server error, sampling. "; - ex.printStackTrace(); - logger.info(ex.getMessage()); - }finally { - if(rs!=null) try{rs.close();}catch(SQLException ex){} - if(stt!=null) try{stt.close();}catch(SQLException ex){} - } + 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 ret = jdbcTemplate.query(sql_query, parameters, new DBTools.JsonRowMapper()); + List> 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", ""); 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", "/api/locust/v01/get_checkpoints"},method = RequestMethod.POST, produces = "application/json;charset=UTF-8") + @ResponseBody + public ResponseEntity 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 = 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 { + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + if (conn != null) { + logger.info("Connect is OK!"); + } else { + throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true); + } + } catch (Exception ex) { + throw new CustomException(200, 10000, trt.trt(false, "An error occurred while connecting to the database!"), UUID.randomUUID().toString(),true); + } + + try { + Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + //st.executeUpdate("SET TIME ZONE 'UTC';"); зачем коментил? + stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); + stt0.close(); + } catch (SQLException ex) { + throw new CustomException(200, 10000, trt.trt(false, "Failed to execute SQL query!"), UUID.randomUUID().toString(),true); + } + + JSONObject doc=null; + InputStream body; + if(reqData!=null) { + + + body = new ByteArrayInputStream(reqData); + + String text=""; + try { + text = new String(body.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + logger.info(text); + + //JSONParser jsonParser = new JSONParser(); + //doc = (JSONObject)jsonParser.parse(text); + //doc = new JSONObject(body); + doc = new JSONObject(text); + } + + JSONArray array=new JSONArray(); //Результирующий набор данных + + String sql_query = ""; + Statement stt=null; + ResultSet rs=null; + try { + stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + sql_query = """ + select + f.id, + f.country_id, + u.name as user_name, + f.lat, + f.lon, + f.radius, + f.name, + f.temperature_soil, + f.temperature_air + from + main.frmcheckpoints f + left join main._users u on u.id=f.user_id + where + f.del=false + and (${country_id} is null or (${country_id}=-1 and f.country_id in (7,3,4,2)) or (${country_id}=-2 and f.country_id in (7,1,5,6,8,9,10)) or ${country_id}=f.country_id) + order by f.id desc;"""; + + PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); + if(doc!=null) { + //stmtn.setInt("_user_id", Integer.parseInt(user.id)); + + if(doc.isNull("country_id")) stmtn.setNULLInt("country_id"); + else stmtn.setInt("country_id",doc.getInt("country_id")); + } + PreparedStatement stmt=stmtn.getPreparedStatement(); + + rs = stmt.executeQuery(); + if (rs != null) { + try { + while(rs.next()) { + + JSONObject obj = new JSONObject(); + obj.put("id", rs.getLong("id")); + + double lat=0; + double lon=0; + lat=rs.getDouble("lat"); + lon=rs.getDouble("lon"); + obj.put("user_name", rs.getString("user_name")); + obj.put("name", rs.getString("name")); + obj.put("lat", lat); + obj.put("lon", lon); + obj.put("radius", rs.getFloat("radius")); + obj.put("temperature_soil", rs.getFloat("temperature_soil")); + obj.put("temperature_air", rs.getFloat("temperature_air")); + array.put(obj); + } + rs.close(); + } catch (SQLException ex) { + 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) { + 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){} + } + + + 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); } } //Получить плотность личинок за последние 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; - try { - Class.forName("org.postgresql.Driver"); - conn = DriverManager.getConnection(db_url, db_login, db_password); - if (conn != null) { - logger.info("Connect is OK!"); - } else { - errorCode=1; - errorMessage+="An error occurred while connecting to the database!"; - } - } catch (Exception ex) { - logger.info(ex.getMessage()); - errorCode=1; - errorMessage+="An error occurred while connecting to the database!"; - } - - try { - Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - stt0.executeUpdate("SET TIME ZONE 'UTC';"); //зачем коментил? - //stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем нужно вообще? - stt0.close(); - } catch (SQLException ex) { - logger.info(ex.getMessage()); - errorCode=1; - errorMessage+="Failed to execute SQL query!"; - } - - - JSONArray array=new JSONArray(); //Результирующий набор данных - - String sql_query = ""; - Statement stt=null; - ResultSet rs=null; - try { - stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - sql_query = """ - select * from main.get_density_larval(${id}); - """; - PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); - stmtn.setInt("id",id); - PreparedStatement stmt=stmtn.getPreparedStatement(); - - rs = stmt.executeQuery(); - if (rs != null) { - try { - while(rs.next()) { - JSONObject obj = new JSONObject(); - obj.put("year", rs.getLong(1)); - obj.put("density", rs.getFloat(2)); - array.put(obj); - } - rs.close(); - } catch (SQLException ex) { - errorCode=1; - errorMessage+="Internal server error"; - ex.printStackTrace(); - logger.info(ex.getMessage()); + public ResponseEntity 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); } - } - } catch (SQLException ex) { - errorCode=1; - errorMessage+="Internal server error"; - ex.printStackTrace(); - logger.info(ex.getMessage()); - }finally { - if(rs!=null) try{rs.close();}catch(SQLException ex){} - if(stt!=null) try{stt.close();}catch(SQLException ex){} - } - - if(errorCode!=0) { - JSONObject obj = new JSONObject(); - obj.put("error_code",errorCode); - obj.put("error_message", errorMessage); - return obj.toString(); - }else { - JSONObject obj = new JSONObject(); - obj.put("error_code",0); - obj.put("error_message", "test"); - obj.put("data",array); - return obj.toString(); - } - } - - //Получить плотность имаго за последние 5 лет - @RequestMapping(value = "/get_density_imago",method = RequestMethod.POST, produces = "application/json;charset=UTF-8") - @ResponseBody - public String getDensityImago(@ModelAttribute User user,@RequestParam(required=false,name="id") Integer id,@RequestParam(required=false,name="lng") String language_id) { - int errorCode=0; - String errorMessage=""; - - Connection conn = null; - try { - Class.forName("org.postgresql.Driver"); - conn = DriverManager.getConnection(db_url, db_login, db_password); - if (conn != null) { - logger.info("Connect is OK!"); - } else { - errorCode=1; - errorMessage+="An error occurred while connecting to the database!"; - } - } catch (Exception ex) { - logger.info(ex.getMessage()); - errorCode=1; - errorMessage+="An error occurred while connecting to the database!"; - } - - try { - Statement stt0 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - stt0.executeUpdate("SET TIME ZONE 'UTC';"); //зачем коментил? - //stt0.executeUpdate("SET TIME ZONE 'Asia/Almaty';"); //Зачем нужно вообще? - stt0.close(); - } catch (SQLException ex) { - logger.info(ex.getMessage()); - errorCode=1; - errorMessage+="Failed to execute SQL query!"; - } - - - JSONArray array=new JSONArray(); //Результирующий набор данных - - String sql_query = ""; - Statement stt=null; - ResultSet rs=null; - try { - stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - sql_query = """ - select * from main.get_density_imago(${id}); - """; - PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); - stmtn.setInt("id",id); - PreparedStatement stmt=stmtn.getPreparedStatement(); - - rs = stmt.executeQuery(); - if (rs != null) { + Jws claims = null; + PublicKey key_a = getPublicKey(); 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()); + 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(); } - } 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){} - } + JSONArray array=new JSONArray(); //Результирующий набор данных + String sql_query = """ + select * from main.get_density_larval(:id); + """; + MapSqlParameterSource parameters = new MapSqlParameterSource(); + parameters.addValue("id", id); + List ret = jdbcTemplate.query(sql_query, parameters, new DBTools.JsonRowMapper()); + List> 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", ""); 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 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 = 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 ret = jdbcTemplate.query(sql_query, parameters, new DBTools.JsonRowMapper()); + List> 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; + } + //--------------------------------------------------------------------------- } diff --git a/src/main/java/org/ccalm/main/QGIS.java b/src/main/java/org/ccalm/main/QGIS.java index 045b610..5991d1a 100644 --- a/src/main/java/org/ccalm/main/QGIS.java +++ b/src/main/java/org/ccalm/main/QGIS.java @@ -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 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) { diff --git a/src/main/java/org/ccalm/main/SendMail.java b/src/main/java/org/ccalm/main/SendMail.java index aa02e76..b25003d 100644 --- a/src/main/java/org/ccalm/main/SendMail.java +++ b/src/main/java/org/ccalm/main/SendMail.java @@ -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) { diff --git a/src/main/java/org/ccalm/main/SendWarning.java b/src/main/java/org/ccalm/main/SendWarning.java index a066d77..b7c0aa9 100644 --- a/src/main/java/org/ccalm/main/SendWarning.java +++ b/src/main/java/org/ccalm/main/SendWarning.java @@ -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 request = new HashMap<>(); @@ -73,45 +74,82 @@ 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 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> entity = new HttpEntity<>(request, headers); + String url = "https://geoserver2.ccalm.org/geodatalist/getSoilTemperature"; + try { + ResponseEntity 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 send() { Map result = new HashMap<>(); result.put("error_code", 0); try { - String sql = """ - select + String sql = """ + select t.uid, t.user_uid, - t.lat, - t.lon, - t.temperature as value, + t.lat, + t.lon, u.email, - l.short_name - from - main.frmcheckpoints t + 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 - """; - MapSqlParameterSource parameters = new MapSqlParameterSource(); - //parameters.addValue("language_id", language_id, Types.INTEGER); - List 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) { + where + t.del=false + and (t.warn_soil=true or t.warn_air=true) + """; + MapSqlParameterSource parameters = new MapSqlParameterSource(); + //parameters.addValue("language_id", language_id, Types.INTEGER); + List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); + for (String jsonString : ret) { + JSONObject obj = new JSONObject(jsonString); + + 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,24 +170,24 @@ public class SendWarning { .append("") .append("
") .append("") // Логотип - .append("

").append(trt.trt("Warning")).append("

") - .append("

").append(trt.trt("The_soil_temperature_has_exceeded_the_set_value")).append(": ").append(value).append("

") + .append("

").append(trt.trt(true,"Warning")).append("

") + .append("

").append(trt.trt(true,"The_soil_temperature_has_exceeded_the_set_value")).append(": ").append(value).append("

") .append("") - .append("") - .append("") + .append("") + .append("") .append("
").append(trt.trt("Date")).append("").append(tmp.getString("date")).append("
").append(trt.trt("Value")).append("").append(tmp.getDouble("value")).append(" °C
").append(trt.trt(true,"Date")).append("").append(tmp_air.getString("date")).append("
").append(trt.trt(true,"Value")).append("").append(tmp_air.getDouble("value")).append(" °C
") - .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("
") // Закрываем контейнер .append("") .append(""); 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(); - } + } if(send) { sql= """ update @@ -162,15 +200,78 @@ public class SendWarning { param.addValue("uid", obj.getString("uid"), Types.INTEGER); int rowsUpdated = jdbcTemplate.update(sql, param); System.out.println("rowsUpdated = "+String.valueOf(rowsUpdated)); - } - } + } + } } } + + 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("") + .append("") + .append("") + .append("") + .append("") + .append("
") + .append("") // Логотип + .append("

").append(trt.trt(true,"Warning")).append("

") + .append("

").append(trt.trt(true,"The_soil_temperature_has_exceeded_the_set_value")).append(": ").append(value).append("

") + .append("") + .append("") + .append("") + .append("
").append(trt.trt(true,"Date")).append("").append(tmp_soil.getString("date")).append("
").append(trt.trt(true,"Value")).append("").append(tmp_soil.getDouble("value")).append(" °C
") + .append(trt.trt(true,"To_resume_monitoring_please_set_the_warn_field_to_true")) + .append("
") // Закрываем контейнер + .append("") + .append(""); + + 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); } + + } diff --git a/src/main/java/org/ccalm/main/SessionController.java b/src/main/java/org/ccalm/main/SessionController.java index 4dc3dc1..1641b89 100644 --- a/src/main/java/org/ccalm/main/SessionController.java +++ b/src/main/java/org/ccalm/main/SessionController.java @@ -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) { diff --git a/src/main/java/org/ccalm/main/SingleLineThrowableProxyConverter.java b/src/main/java/org/ccalm/main/SingleLineThrowableProxyConverter.java new file mode 100644 index 0000000..0072bbb --- /dev/null +++ b/src/main/java/org/ccalm/main/SingleLineThrowableProxyConverter.java @@ -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", " "); + } +} diff --git a/src/main/java/org/ccalm/main/SpringContext.java b/src/main/java/org/ccalm/main/SpringContext.java new file mode 100644 index 0000000..469b6e5 --- /dev/null +++ b/src/main/java/org/ccalm/main/SpringContext.java @@ -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; + } +} diff --git a/src/main/java/org/ccalm/main/TestFiles.java b/src/main/java/org/ccalm/main/TestFiles.java index 478c173..3c545f4 100644 --- a/src/main/java/org/ccalm/main/TestFiles.java +++ b/src/main/java/org/ccalm/main/TestFiles.java @@ -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() { diff --git a/src/main/java/org/ccalm/main/TranslationController.java b/src/main/java/org/ccalm/main/TranslationController.java index b959ce1..78c20f9 100644 --- a/src/main/java/org/ccalm/main/TranslationController.java +++ b/src/main/java/org/ccalm/main/TranslationController.java @@ -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 getTranslations( @CookieValue(value = "lng", defaultValue = "1") String language_id ) { - Map translations = new HashMap<>(); try { diff --git a/src/main/java/org/ccalm/main/api/APICountries.java b/src/main/java/org/ccalm/main/api/APICountries.java new file mode 100644 index 0000000..5eb17c0 --- /dev/null +++ b/src/main/java/org/ccalm/main/api/APICountries.java @@ -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> downloadCountries() { + String apiUrl = "https://api.worldbank.org/v2/country?format=json&per_page=600"; + + List> countriesList = new ArrayList<>(); + + try { + // 1. Запрос данных с API + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity 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 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 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 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 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> 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); + } + } + +} diff --git a/src/main/java/org/ccalm/main/engine/EngineController.java b/src/main/java/org/ccalm/main/engine/EngineController.java index f76d235..6d37287 100644 --- a/src/main/java/org/ccalm/main/engine/EngineController.java +++ b/src/main/java/org/ccalm/main/engine/EngineController.java @@ -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 = 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 diff --git a/src/main/java/org/ccalm/main/login/LoginController.java b/src/main/java/org/ccalm/main/login/LoginController.java deleted file mode 100644 index 7574eca..0000000 --- a/src/main/java/org/ccalm/main/login/LoginController.java +++ /dev/null @@ -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 ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); - for (int i = 0; i < ret.size(); i++) { - JSONObject json = new JSONObject(ret.get(i)); - model.addAttribute(json.getString("identifier"), json.getString("identifier")); - } - } catch (Exception ex) { - String uuid = UUID.randomUUID().toString(); - logger.error(uuid, ex); - } - - return "login/login"; - } - -} diff --git a/src/main/java/org/ccalm/main/models/ErrorResponseModel.java b/src/main/java/org/ccalm/main/models/ErrorResponseModel.java index f8bab65..85ffab5 100644 --- a/src/main/java/org/ccalm/main/models/ErrorResponseModel.java +++ b/src/main/java/org/ccalm/main/models/ErrorResponseModel.java @@ -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 errorMessage, String errorMarker) { + public ErrorResponseModel(int httpCode, int errorCode, List 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 errorMessage, List errorSetting, String errorMarker) { + public ErrorResponseModel(int httpCode, int errorCode, List errorMessage, List 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; } diff --git a/src/main/java/org/ccalm/main/utils/CustomException.java b/src/main/java/org/ccalm/main/utils/CustomException.java index 27c0e51..ae71a43 100644 --- a/src/main/java/org/ccalm/main/utils/CustomException.java +++ b/src/main/java/org/ccalm/main/utils/CustomException.java @@ -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 errorMessages, String marker, boolean saveToLog) { + public CustomException(int httpCode, int errorCode, List 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 errorMessages, List errorSettings, String marker, boolean saveToLog) { + public CustomException(int httpCode, int errorCode, List errorMessages, List 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(); } diff --git a/src/main/java/org/ccalm/main/utils/Tools.java b/src/main/java/org/ccalm/main/utils/Tools.java index 7d01d8b..8b4b200 100644 --- a/src/main/java/org/ccalm/main/utils/Tools.java +++ b/src/main/java/org/ccalm/main/utils/Tools.java @@ -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; } diff --git a/src/main/java/tools/Translation.java b/src/main/java/tools/Translation.java index ab31a7e..5b8a403 100644 --- a/src/main/java/tools/Translation.java +++ b/src/main/java/tools/Translation.java @@ -32,29 +32,33 @@ public class Translation { this.jdbcTemplate = jdbcTemplate; } - public String trt(String text){ - String sql = """ - select - translation - from - main._translations - where - del=false - and language_id=:language_id - and identifier=:identifier; - """; - MapSqlParameterSource parameters = new MapSqlParameterSource(); - parameters.addValue("language_id", language_id); - parameters.addValue("identifier", text); - List ret = jdbcTemplate.query(sql, parameters, new tools.DBTools.JsonRowMapper()); - int i = 0; - for (i = 0; i < ret.size(); i++) { - JSONObject json = new JSONObject(ret.get(i)); - text = json.getString("translation"); - } - if(i==0){ - text = text.replace("_", " "); + public String trt(boolean translate,String text){ + if(translate) { + String sql = """ + select + translation + from + main._translations + where + del=false + and language_id=:language_id + and identifier=:identifier; + """; + MapSqlParameterSource parameters = new MapSqlParameterSource(); + parameters.addValue("language_id", language_id); + parameters.addValue("identifier", text); + List ret = jdbcTemplate.query(sql, parameters, new tools.DBTools.JsonRowMapper()); + int i = 0; + for (i = 0; i < ret.size(); i++) { + JSONObject json = new JSONObject(ret.get(i)); + text = json.getString("translation"); + } + if(i==0){ + text = text.replace("_", " "); + } + return text; + }else { + return text; } - return text; } } diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml index e8b1b8e..3c6abcf 100644 --- a/src/main/resources/logback-spring.xml +++ b/src/main/resources/logback-spring.xml @@ -1,13 +1,15 @@ + + ${LOGS}/${appName}.log - {"timestamp":"%d{yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}","thread":"[%thread]","level":"%level","logger":"%logger{36}","message":"%msg"}%n + {"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 ${LOGS}/${appName}.%d{yyyy-MM-dd}.%i.log diff --git a/src/main/resources/templates/engine/index.html b/src/main/resources/templates/engine/index.html index a4ceba4..daa2bfe 100644 --- a/src/main/resources/templates/engine/index.html +++ b/src/main/resources/templates/engine/index.html @@ -17,6 +17,7 @@ + @@ -26,7 +27,7 @@ - + @@ -40,7 +41,7 @@ - + - @@ -373,6 +376,7 @@ function onLoadPage() {{name}} {{patronymic}} {{surname}} ({{ roles.join(', ') }}) Language + - -
- - -
-
- -
- - - - - - - - - - - - - - - - - - - diff --git a/src/main/resources/templates/test.html b/src/main/resources/templates/test.html index a24c415..aee861f 100644 --- a/src/main/resources/templates/test.html +++ b/src/main/resources/templates/test.html @@ -8,7 +8,7 @@ - +