From 686109361f048ddd2fc5ed7f337d9f84280a8699 Mon Sep 17 00:00:00 2001 From: igor Date: Tue, 15 Jul 2025 07:40:21 +0500 Subject: [PATCH] Import mod --- org-ccalm-main.yml | 4 +- src/main/java/org/ccalm/main/AcceptJSON.java | 2193 +++++++++-------- .../org/ccalm/main/models/FrmLocustModel.java | 2 +- src/main/resources/templates/index.html | 4 +- 4 files changed, 1126 insertions(+), 1077 deletions(-) diff --git a/org-ccalm-main.yml b/org-ccalm-main.yml index f73da5a..8b9683f 100644 --- a/org-ccalm-main.yml +++ b/org-ccalm-main.yml @@ -10,9 +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://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/src/main/java/org/ccalm/main/AcceptJSON.java b/src/main/java/org/ccalm/main/AcceptJSON.java index b0f5f98..eaac883 100644 --- a/src/main/java/org/ccalm/main/AcceptJSON.java +++ b/src/main/java/org/ccalm/main/AcceptJSON.java @@ -37,7 +37,6 @@ import com.zaxxer.hikari.HikariDataSource; import jakarta.servlet.ServletContext; import org.ccalm.main.models.FrmLocustModel; import org.ccalm.main.utils.CustomException; -import org.ccalm.main.utils.LTools; import org.json.JSONObject; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; @@ -61,6 +60,9 @@ import org.springframework.web.multipart.MultipartFile; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; +import tctable.Tools; +import tools.DBTools; +import tools.User; //import com.google.common.io.CharStreams; @@ -69,9 +71,9 @@ import org.w3c.dom.NodeList; //import sun.nio.cs.StandardCharsets; //import kz.locust.CCALM.AcceptEXCEL.Locust; //import kz.locust.CCALM.AcceptEXCEL.Locust; -import tctable.Tools; -import tools.DBTools; -import tools.User; +//import tctable.Tools; +//import tools.DBTools; +//import tools.User; @Controller //@SessionAttributes( { "user" }) //Сесионный объект @@ -124,300 +126,318 @@ public class AcceptJSON implements ServletContextAware { */ @ResponseBody @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! - if(user.id==null || user.id.equals("null") || user.id.isBlank()) - return "Please log in!"; - - Connection conn = null; - try { - Class.forName("org.postgresql.Driver"); - conn = DriverManager.getConnection(db_url, db_login, db_password); - } catch (Exception ex) { - ex.printStackTrace(); - } - - StringBuilder sb = new StringBuilder(1024); - try - { - String strURL="http://91.185.13.233:98/get_fito"; - URL url = new URL(strURL); - HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); - hConn.setRequestMethod("GET"); - hConn.setRequestProperty("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEyMyIsInVzZXJuYW1lIjoiQ0NBTE0iLCJyb2xlIjoidXNlciIsImlhdCI6MTcwNjc4NjQ0Nn0.bypDbAZYjbQu8hWrb6MnnAZ80AbO4ZifP3inEnpbabI"); - - hConn.connect(); - int responseCode = hConn.getResponseCode(); - if (responseCode / 100 == 2) //Code 206 is "Partial Content" - { - InputStreamReader inputStream = new InputStreamReader(hConn.getInputStream(), "UTF-8"); - int bytesRead; - char[] buffer = new char[BUFFER_SIZE]; - while ((bytesRead = inputStream.read(buffer)) != -1) { - sb.append(new String(buffer,0,bytesRead)); - } - inputStream.close(); - } - }catch (IOException e) - { - e.printStackTrace(); - } - - String content=sb.toString(); - - - int year=2024; + 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 + ) { int cnt=0; - if(content==null || content.isEmpty()) { - System.out.println("Content is null"); - }else { - System.out.println("Start"); - - String sql="delete from main.frmlocust where country_id=5 and eid=0 and extract(year from date)="+String.valueOf(year); - try{ - PreparedStatement stmt = conn.prepareStatement(sql); - int cont = stmt.executeUpdate(); - System.out.println("cnt: " + String.valueOf(cont)); - } catch (SQLException e) { - e.printStackTrace(); - } + try{ + //TODO add user verification: that he is authorized and that he is an administrator! + //if(user.id==null || user.id.equals("null") || user.id.isBlank()) + // return "Please log in!"; - //System.out.println(content); - //Iterate over the elements of the array. - JSONObject jsonObject= new JSONObject(content); - JSONArray jsonArray = jsonObject.getJSONArray("data"); - for (Object o : jsonArray) { - JSONObject jsonObj = (JSONObject) o; + Connection conn = null; + try { + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + } catch (Exception ex) { + ex.printStackTrace(); + } - //I don't miss other dates - ZonedDateTime dateTime = ZonedDateTime.parse(jsonObj.getString("examination_date"), DateTimeFormatter.ISO_ZONED_DATE_TIME); - if(dateTime.getYear()!=year) - continue; + StringBuilder sb = new StringBuilder(1024); + try + { + String strURL="http://91.185.13.233:98/get_fito"; + URL url = new URL(strURL); + HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); + hConn.setRequestMethod("GET"); + hConn.setRequestProperty("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEyMyIsInVzZXJuYW1lIjoiQ0NBTE0iLCJyb2xlIjoidXNlciIsImlhdCI6MTcwNjc4NjQ0Nn0.bypDbAZYjbQu8hWrb6MnnAZ80AbO4ZifP3inEnpbabI"); - sql=""" - insert into main.frmlocust( - eid, --1 - lat_center, --2 - lon_center, --3 - lat1, --4 - lon1, --5 - date, --6 - village, --7 - terrain, --8 - district, --9 - country_id, --10 - region_id, --11 - locust_type_id, --12 - bio_hectare, --13 - locust_populated, --14 - description, --15 - eggs, --16 - hoppers, --17 - bands, --18 - adults, --19 - swarms --20 - )values( - ?, --1 eid - ?, --2 lat_center - ?, --3 lon_center - ?, --4 lat1 - ?, --5 lon1 - TO_TIMESTAMP(?, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), --6 date - LEFT(?, 100), --7 village - LEFT(?, 100), --8 terrain - LEFT(?, 100), --9 district - ?, --10 country_id - ?, --11 region_id - ?, --12 locust_type_id - ?, --13 bio_hectare - ?, --14 locust_populated - ?, --15 description - ?, --16 eggs CheckBox - ?, --17 hoppers CheckBox - ?, --18 bands CheckBox - ?, --19 adults CheckBox - ? --20 swarms CheckBox - )"""; - PreparedStatement stmt=null; - try { - stmt = conn.prepareStatement(sql); - } catch (SQLException ex) { - ex.printStackTrace(); - model.addAttribute("PreviewTable","Error prepare 2"); - return "json"; - } + hConn.setConnectTimeout(60000); // 60 сек - String description=""; - description += "city: "+jsonObj.getString("city")+"\n"; - description += "message_type: "+jsonObj.getString("message_type")+"\n"; - if(jsonObj.has("development_stage") && !jsonObj.isNull("development_stage")) - description += "stage: "+jsonObj.getString("development_stage")+"\n"; - - try { - stmt.setLong(1, 0); - stmt.setDouble(2,jsonObj.getDouble("latitude")); - stmt.setDouble(3,jsonObj.getDouble("longitude")); - stmt.setDouble(4,jsonObj.getDouble("latitude")); - stmt.setDouble(5,jsonObj.getDouble("longitude")); - stmt.setString(6,jsonObj.getString("examination_date")); //2023-03-20T06:23:20.000Z - if(jsonObj.has("village") && !jsonObj.isNull("village")) - stmt.setString(7,jsonObj.getString("village")); - else - stmt.setNull(7, Types.VARCHAR); - if(jsonObj.has("farm") && !jsonObj.isNull("farm")) - stmt.setString(8,jsonObj.getString("farm")); - else - stmt.setNull(8, Types.VARCHAR); - if(jsonObj.has("district") && !jsonObj.isNull("district")) - stmt.setString(9,jsonObj.getString("district")); - else - stmt.setNull(9, Types.VARCHAR); - - stmt.setInt(10,5); //country_id - - - int region_id=-1; - switch (jsonObj.getString("region")) { - case "Туркестанская": //5 false -215739 1691403679 5 "Түркістан облысы (Туркестанская область)" - region_id=5; - break; - case "Жамбылская": //4 false -215722 1691403679 5 "Жамбыл облысы (Жамбылская область)" - region_id=4; - break; - case "Алматинская": //3 false -215718 1691403679 5 "Алматы облысы (Алматинская область)" - region_id=3; - break; - case "Карагандинская": //2 false -215776 1691403679 5 "Қарағанды облысы (Карагандинская область)" - region_id=2; - break; - case "Жетысу": //478 false -14312169 1691403679 5 "Жетісу облысы" - region_id=478; - break; - case "Кызылординская": //6 false -215727 1691403679 5 "Қызылорда облысы (Кызылординская область)" - region_id=6; - break; - case "Атырауская": //13 false -214834 1691403679 5 "Атырау облысы (Атырауская область)" - region_id=13; - break; - case "Западно-Казахстанская": //12 false -215441 1691403679 5 "Батыс Қазақстан облысы (Западно-Казахстанская область)" - region_id=12; - break; - case "Акмолинская": //10 false -215743 1691403679 5 "Ақмола облысы (Акмолинская область)" - region_id=10; - break; - case "Восточно-Казахстанская": //1 false -215699 1691403679 5 "Шығыс Қазақстан облысы (Восточно-Казахстанская область)" - region_id=1; - break; - case "Абай": //477 false -14243026 1691473439 5 "Абай облысы" - region_id=477; - break; - case "Костанайская": //8 false -1288730 1691403679 5 "Қостанай облысы (Костанайская область)" - region_id=8; - break; - case "Павлодарская": //11 false -215772 1691403679 5 "Павлодар облысы (Павлодарская область)" - region_id=11; - break; - case "Северо-Казахстанская": //9 false -215760 1691403679 5 "Солтүстік Қазақстан облысы (Северо-Казахстанская область)" - region_id=9; - break; - case "Актюбинская": //7 false -215683 1691403679 5 "Ақтөбе облысы (Актюбинская область)" - region_id=7; - break; - case "Мангистауская": //14 false -215686 1691403679 5 "Маңғыстау облысы (Мангистауская область)" - region_id=14; - break; - case "Улытау": //479 false -14312737 1691462768 5 "Ұлытау облысы" - region_id=14; - break; - default: - throw new CustomException(200, 10000, "Not find region: " + jsonObj.getString("region"), null, true); + hConn.connect(); + int responseCode = hConn.getResponseCode(); + if (responseCode / 100 == 2) //Code 206 is "Partial Content" + { + InputStreamReader inputStream = new InputStreamReader(hConn.getInputStream(), "UTF-8"); + int bytesRead; + char[] buffer = new char[BUFFER_SIZE]; + while ((bytesRead = inputStream.read(buffer)) != -1) { + sb.append(new String(buffer,0,bytesRead)); } - if(region_id==-1) - stmt.setInt(11,region_id); //region_id - else - stmt.setNull(11, Types.INTEGER); - - //Вид саранчи - int locust_id=-1; - switch (jsonObj.getString("grasshopper_type")) { - case "Мароккская саранча": - locust_id=2; - break; - case "Итальянский прус": - locust_id=1; - break; - case "Азиатская саранча": - locust_id=3; - break; - default: - throw new CustomException(200, 10000, "Not grasshopper_type: " + jsonObj.getString("grasshopper_type"), null, true); - } - stmt.setInt(12,locust_id); //locust_id - - //Обследованно - if(jsonObj.has("examination_area") && !jsonObj.isNull("examination_area")) - stmt.setDouble(13,Double.parseDouble(jsonObj.get("examination_area").toString())); - else - stmt.setNull(13, Types.DOUBLE); - - //Площадь заселения - if(jsonObj.has("settlement_area") && !jsonObj.isNull("settlement_area")) - stmt.setDouble(14,Double.parseDouble(jsonObj.get("settlement_area").toString())); - else - stmt.setNull(14, Types.DOUBLE); - - //Прочее описание - stmt.setString(15,description); //description - - boolean eggs=false; // Яйца - boolean hoppers=false; // Личинки - boolean bands=false; // Кулиги - boolean adults=false; // Имаго - boolean swarms=false; // Стаи - if(jsonObj.has("development_stage") && !jsonObj.isNull("development_stage")) { - if (jsonObj.getString("development_stage").equals("Яйца")) eggs = true; - if (jsonObj.getString("development_stage").equals("Личинки") || jsonObj.getString("development_stage").equals("Заселенность личинками") || jsonObj.getString("development_stage").equals("Личинка")) hoppers = true; - if (jsonObj.getString("development_stage").equals("Кулиги")) bands = true; - if (jsonObj.getString("development_stage").equals("Имаго")) adults = true; - if (jsonObj.getString("development_stage").equals("Стаи")) swarms = true; - } - if(eggs) - stmt.setBoolean(16,true); - else - stmt.setNull(16, Types.BOOLEAN); - if(hoppers) - stmt.setBoolean(17,true); - else - stmt.setNull(17, Types.BOOLEAN); - if(bands) - stmt.setBoolean(18,true); - else - stmt.setNull(18, Types.BOOLEAN); - if(adults) - stmt.setBoolean(19,true); - else - stmt.setNull(19, Types.BOOLEAN); - if(swarms) - stmt.setBoolean(20,true); - else - stmt.setNull(20, Types.BOOLEAN); - - if(region_id!=-1) { - stmt.execute(); - }else { - System.out.println("region: "+jsonObj.getString("region")); - } - } catch (SQLException ex) { - ex.printStackTrace(); - model.addAttribute("PreviewTable","Error set data"); - return "json"; + inputStream.close(); } - cnt++; - } - System.out.println("Proc count = "+String.valueOf(cnt)); - } + }catch (IOException e) + { + e.printStackTrace(); + } + + String content=sb.toString(); + + + int year=2025; + + + if(content==null || content.isEmpty()) { + System.out.println("Content is null"); + }else { + System.out.println("Start"); + + String sql="delete from main.frmlocust where country_id=5 and eid=0 and extract(year from date)="+String.valueOf(year); + try{ + PreparedStatement stmt = conn.prepareStatement(sql); + int cont = stmt.executeUpdate(); + System.out.println("cnt: " + String.valueOf(cont)); + } catch (SQLException e) { + e.printStackTrace(); + } + + //System.out.println(content); + //Iterate over the elements of the array. + JSONObject jsonObject= new JSONObject(content); + JSONArray jsonArray = jsonObject.getJSONArray("data"); + for (Object o : jsonArray) { + JSONObject jsonObj = (JSONObject) o; + + //I don't miss other dates + ZonedDateTime dateTime = ZonedDateTime.parse(jsonObj.getString("examination_date"), DateTimeFormatter.ISO_ZONED_DATE_TIME); + if(dateTime.getYear()!=year) + continue; + + sql=""" + insert into main.frmlocust( + eid, --1 + lat_center, --2 + lon_center, --3 + lat1, --4 + lon1, --5 + date, --6 + village, --7 + terrain, --8 + district, --9 + country_id, --10 + region_id, --11 + locust_type_id, --12 + bio_hectare, --13 + locust_populated, --14 + description, --15 + eggs, --16 + hoppers, --17 + bands, --18 + adults, --19 + swarms --20 + )values( + ?, --1 eid + ?, --2 lat_center + ?, --3 lon_center + ?, --4 lat1 + ?, --5 lon1 + TO_TIMESTAMP(?, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), --6 date + LEFT(?, 100), --7 village + LEFT(?, 100), --8 terrain + LEFT(?, 100), --9 district + ?, --10 country_id + ?, --11 region_id + ?, --12 locust_type_id + ?, --13 bio_hectare + ?, --14 locust_populated + ?, --15 description + ?, --16 eggs CheckBox + ?, --17 hoppers CheckBox + ?, --18 bands CheckBox + ?, --19 adults CheckBox + ? --20 swarms CheckBox + )"""; + PreparedStatement stmt=null; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable","Error prepare 2"); + return "json"; + } + + String description=""; + description += "city: "+jsonObj.getString("city")+"\n"; + description += "message_type: "+jsonObj.getString("message_type")+"\n"; + if(jsonObj.has("development_stage") && !jsonObj.isNull("development_stage")) + description += "stage: "+jsonObj.getString("development_stage")+"\n"; + + try { + stmt.setLong(1, 0); + stmt.setDouble(2,jsonObj.getDouble("latitude")); + stmt.setDouble(3,jsonObj.getDouble("longitude")); + stmt.setDouble(4,jsonObj.getDouble("latitude")); + stmt.setDouble(5,jsonObj.getDouble("longitude")); + stmt.setString(6,jsonObj.getString("examination_date")); //2023-03-20T06:23:20.000Z + if(jsonObj.has("village") && !jsonObj.isNull("village")) + stmt.setString(7,jsonObj.getString("village")); + else + stmt.setNull(7, Types.VARCHAR); + if(jsonObj.has("farm") && !jsonObj.isNull("farm")) + stmt.setString(8,jsonObj.getString("farm")); + else + stmt.setNull(8, Types.VARCHAR); + if(jsonObj.has("district") && !jsonObj.isNull("district")) + stmt.setString(9,jsonObj.getString("district")); + else + stmt.setNull(9, Types.VARCHAR); + + stmt.setInt(10,5); //country_id + + + int region_id=-1; + switch (jsonObj.getString("region")) { + case "Туркестанская": //5 false -215739 1691403679 5 "Түркістан облысы (Туркестанская область)" + region_id=5; + break; + case "Жамбылская": //4 false -215722 1691403679 5 "Жамбыл облысы (Жамбылская область)" + region_id=4; + break; + case "Алматинская": //3 false -215718 1691403679 5 "Алматы облысы (Алматинская область)" + region_id=3; + break; + case "Карагандинская": //2 false -215776 1691403679 5 "Қарағанды облысы (Карагандинская область)" + region_id=2; + break; + case "Жетысу": //478 false -14312169 1691403679 5 "Жетісу облысы" + region_id=478; + break; + case "Кызылординская": //6 false -215727 1691403679 5 "Қызылорда облысы (Кызылординская область)" + region_id=6; + break; + case "Атырауская": //13 false -214834 1691403679 5 "Атырау облысы (Атырауская область)" + region_id=13; + break; + case "Западно-Казахстанская": //12 false -215441 1691403679 5 "Батыс Қазақстан облысы (Западно-Казахстанская область)" + region_id=12; + break; + case "Акмолинская": //10 false -215743 1691403679 5 "Ақмола облысы (Акмолинская область)" + region_id=10; + break; + case "Восточно-Казахстанская": //1 false -215699 1691403679 5 "Шығыс Қазақстан облысы (Восточно-Казахстанская область)" + region_id=1; + break; + case "Абай": //477 false -14243026 1691473439 5 "Абай облысы" + region_id=477; + break; + case "Костанайская": //8 false -1288730 1691403679 5 "Қостанай облысы (Костанайская область)" + region_id=8; + break; + case "Павлодарская": //11 false -215772 1691403679 5 "Павлодар облысы (Павлодарская область)" + region_id=11; + break; + case "Северо-Казахстанская": //9 false -215760 1691403679 5 "Солтүстік Қазақстан облысы (Северо-Казахстанская область)" + region_id=9; + break; + case "Актюбинская": //7 false -215683 1691403679 5 "Ақтөбе облысы (Актюбинская область)" + region_id=7; + break; + case "Мангистауская": //14 false -215686 1691403679 5 "Маңғыстау облысы (Мангистауская область)" + region_id=14; + break; + case "Улытау": //479 false -14312737 1691462768 5 "Ұлытау облысы" + region_id=14; + break; + default: + throw new CustomException(200, 10000, "Not find region: " + jsonObj.getString("region"), null, true); + } + if(region_id==-1) + stmt.setInt(11,region_id); //region_id + else + stmt.setNull(11, Types.INTEGER); + + //Вид саранчи + int locust_id=-1; + switch (jsonObj.getString("grasshopper_type")) { + case "Мароккская саранча": + locust_id=2; + break; + case "Итальянский прус": + locust_id=1; + break; + case "Азиатская саранча": + locust_id=3; + break; + default: + throw new CustomException(200, 10000, "Not grasshopper_type: " + jsonObj.getString("grasshopper_type"), null, true); + } + stmt.setInt(12,locust_id); //locust_id + + //Обследованно + if(jsonObj.has("examination_area") && !jsonObj.isNull("examination_area")) + stmt.setDouble(13,Double.parseDouble(jsonObj.get("examination_area").toString())); + else + stmt.setNull(13, Types.DOUBLE); + + //Площадь заселения + if(jsonObj.has("settlement_area") && !jsonObj.isNull("settlement_area")) + stmt.setDouble(14,Double.parseDouble(jsonObj.get("settlement_area").toString())); + else + stmt.setNull(14, Types.DOUBLE); + + //Прочее описание + stmt.setString(15,description); //description + + boolean eggs=false; // Яйца + boolean hoppers=false; // Личинки + boolean bands=false; // Кулиги + boolean adults=false; // Имаго + boolean swarms=false; // Стаи + if(jsonObj.has("development_stage") && !jsonObj.isNull("development_stage")) { + if (jsonObj.getString("development_stage").equals("Яйца")) eggs = true; + if (jsonObj.getString("development_stage").equals("Личинки") || jsonObj.getString("development_stage").equals("Заселенность личинками") || jsonObj.getString("development_stage").equals("Личинка")) hoppers = true; + if (jsonObj.getString("development_stage").equals("Кулиги")) bands = true; + if (jsonObj.getString("development_stage").equals("Имаго")) adults = true; + if (jsonObj.getString("development_stage").equals("Стаи")) swarms = true; + } + if(eggs) + stmt.setBoolean(16,true); + else + stmt.setNull(16, Types.BOOLEAN); + if(hoppers) + stmt.setBoolean(17,true); + else + stmt.setNull(17, Types.BOOLEAN); + if(bands) + stmt.setBoolean(18,true); + else + stmt.setNull(18, Types.BOOLEAN); + if(adults) + stmt.setBoolean(19,true); + else + stmt.setNull(19, Types.BOOLEAN); + if(swarms) + stmt.setBoolean(20,true); + else + stmt.setNull(20, Types.BOOLEAN); + + if(region_id!=-1) { + stmt.execute(); + }else { + System.out.println("region: "+jsonObj.getString("region")); + } + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable","Error set data"); + return "json"; + } + cnt++; + } + System.out.println("Proc count = "+String.valueOf(cnt)); + } + } catch (CustomException e) { + if(e.isSaveToLog()) { + String uuid = UUID.randomUUID().toString(); + logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e); + } + } catch (Exception ex) { + String uuid = UUID.randomUUID().toString(); + logger.error(MarkerFactory.getMarker(uuid), ex.getMessage(), ex); + } return "Proc count = "+String.valueOf(cnt); } @@ -431,655 +451,356 @@ public class AcceptJSON implements ServletContextAware { */ @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; - try { - Class.forName("org.postgresql.Driver"); - conn = DriverManager.getConnection(db_url, db_login, db_password); - } catch (Exception ex) { - ex.printStackTrace(); - } - - //Set UTC time - Statement stm=null; - try { - stm = conn.createStatement(); + try{ + Connection conn = null; try { - stm.execute("SET timezone TO 'UTC';"); - } catch( SQLException ex ) { - ex.printStackTrace(); + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + } catch (Exception ex) { + throw new CustomException(200, 10000, ex.getMessage(),null,true); } - stm.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - - String sqlData=""; - String table=""; - table+=""; - - //Выбираю максимальную дату проверяю что она меньше текущей минус 2 дня и пытаюсь загрузить её - LocalDate lastDate = null;// = LocalDate.parse("2018-05-05"); - Statement stt = null; - ResultSet rs = null; - try { - stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - rs = stt.executeQuery("select to_char(max(date), 'YYYY-MM-DD') as date from integration.days_ru"); - if (rs != null) { + //Set UTC time + Statement stm=null; + try { + stm = conn.createStatement(); try { - if (rs.next()) { - String value = rs.getString(1); - if(value!=null) - lastDate = LocalDate.parse(value); - } - rs.close(); - } catch (SQLException ex) { - ex.printStackTrace(); + stm.execute("SET timezone TO 'UTC';"); + } catch( SQLException ex ) { + throw new CustomException(200, 10000, ex.getMessage(),null,true); + } + stm.close(); + } catch (SQLException ex) { + throw new CustomException(200, 10000, ex.getMessage(),null,true); + } + + + String sqlData=""; + String table="
Ext idLatitude (Широта)Longitude (Долгота)Oblast (область)District (Район)Сельский округХозяйство или местностьВид саранчиФазаЭПВЗаселено ГаДата
"; + table+=""; + + //I select the maximum date, check that it is less than the current minus 2 days and try to load it + LocalDate lastDate = null; + String sql= """ + select to_char(max(date), 'YYYY-MM-DD') as date from integration.days_ru + """; + MapSqlParameterSource parameters = new MapSqlParameterSource(); + //parameters.addValue("user_id", claims.getBody().get("user_id")); + List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); + List data = new ArrayList<>(); + for (String s : ret) { + JSONObject obj = new JSONObject(s); + if(!obj.isNull("date")) { + lastDate = LocalDate.parse(obj.getString("date")); } } - } catch (SQLException ex) { - ex.printStackTrace(); - }finally { - if(rs!=null) try{rs.close();}catch(SQLException ex){ ex.printStackTrace(); } - if(stt!=null) try{stt.close();}catch(SQLException ex){ ex.printStackTrace(); } - } - if(lastDate==null) lastDate = LocalDate.parse("2024-01-10"); + if(lastDate==null) + lastDate = LocalDate.parse("2025-04-01"); + + Statement stt = null; + ResultSet rs = null; + + //Выбираю максимальную дату проверяю что она меньше текущей минус 2 дня и пытаюсь загрузить её + /*LocalDate lastDate = null; + Statement stt = null; + ResultSet rs = null; + try { + stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + rs = stt.executeQuery("select to_char(max(date), 'YYYY-MM-DD') as date from integration.days_ru"); + if (rs != null) { + try { + if (rs.next()) { + String value = rs.getString(1); + if(value!=null) + lastDate = LocalDate.parse(value); + } + rs.close(); + } catch (SQLException ex) { + throw new CustomException(200, 10000, ex.getMessage(),null,true); + } + } + } catch (SQLException ex) { + throw new CustomException(200, 10000, ex.getMessage(),null,true); + }finally { + if(rs!=null) try{rs.close();}catch(SQLException ex){ ex.printStackTrace(); } + if(stt!=null) try{stt.close();}catch(SQLException ex){ ex.printStackTrace(); } + } + if(lastDate==null) lastDate = LocalDate.parse("2025-04-01");*/ - //By number of day downloading data and write result of downloading to database, try or false, after repair need repeat download - while(lastDate.isBefore(LocalDate.now().minusDays(3))){ - lastDate=lastDate.plusDays(1); + //By number of day downloading data and write result of downloading to database, try or false, after repair need repeat download + while(lastDate.isBefore(LocalDate.now().minusDays(3))){ + lastDate=lastDate.plusDays(1); - String dateBegin=lastDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")); - String dateEnd=dateBegin; + String dateBegin=lastDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")); + String dateEnd=dateBegin; - System.out.println( "date = " + dateEnd ); + System.out.println( "date = " + dateEnd ); - //Download JSON data from server - StringBuilder sb = new StringBuilder(); - try - { - String strURL="https://rscagex.ru/pmon/rest/getPhytomons?token=QVOUE97HBSI6LBSGJGQZMP3KPSS1QK&dateBegin="+dateBegin+"&dateEnd="+dateEnd; - URL url = new URL(strURL); - HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); - hConn.setRequestMethod("GET"); - hConn.connect(); - int responseCode = hConn.getResponseCode(); - if (responseCode / 100 == 2) //Code 206 is "Partial Content" + //Download JSON data from server + StringBuilder sb = new StringBuilder(); + try { - //InputStream inputStream = hConn.getInputStream(); - InputStreamReader inputStream = new InputStreamReader(hConn.getInputStream(), "UTF-8"); - int bytesRead; - char[] buffer = new char[BUFFER_SIZE]; - while ((bytesRead = inputStream.read(buffer)) != -1) { - sb.append(new String(buffer,0,bytesRead)); + String strURL="https://rscagex.ru/pmon/rest/getPhytomons?token=QVOUE97HBSI6LBSGJGQZMP3KPSS1QK&dateBegin="+dateBegin+"&dateEnd="+dateEnd; + URL url = new URL(strURL); + HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); + hConn.setRequestMethod("GET"); + hConn.connect(); + int responseCode = hConn.getResponseCode(); + if (responseCode / 100 == 2) //Code 206 is "Partial Content" + { + //InputStream inputStream = hConn.getInputStream(); + InputStreamReader inputStream = new InputStreamReader(hConn.getInputStream(), "UTF-8"); + int bytesRead; + char[] buffer = new char[BUFFER_SIZE]; + while ((bytesRead = inputStream.read(buffer)) != -1) { + sb.append(new String(buffer,0,bytesRead)); + } + inputStream.close(); } - inputStream.close(); - } - hConn.disconnect(); - } - catch (IOException e) - { - e.printStackTrace(); - } - String content=sb.toString(); - if(content!=null && !content.isEmpty()) { + hConn.disconnect(); + } + catch (IOException ex) + { + throw new CustomException(200, 10000, ex.getMessage(),null,true); + } + String content=sb.toString(); + if(content!=null && !content.isEmpty()) { - //byte[] data = sb.toByteArray(in); - //String content=new String(data, Charsets.UTF_8); + //byte[] data = sb.toByteArray(in); + //String content=new String(data, Charsets.UTF_8); - //Iterate over the elements of the array. - int cntO = 1; - int cntV = 1; - JSONArray jsonArray = new JSONArray(content); - for (Object o : jsonArray) { - JSONObject jsonObj = (JSONObject) o; - FrmLocustModel locust = new FrmLocustModel(); + //Iterate over the elements of the array. + int cntO = 1; + int cntV = 1; + JSONArray jsonArray = new JSONArray(content); + for (Object o : jsonArray) { + JSONObject jsonObj = (JSONObject) o; + FrmLocustModel locust = new FrmLocustModel(); - locust.date = jsonObj.getString("date"); + locust.date = jsonObj.getString("date"); - String regionName=""; - if (!jsonObj.isNull("regionName")) - regionName = jsonObj.getString("regionName"); + String regionName=""; + if (!jsonObj.isNull("regionName")) + regionName = jsonObj.getString("regionName"); - if (!jsonObj.isNull("townName")) - locust.district = jsonObj.getString("townName"); + if (!jsonObj.isNull("townName")) + locust.district = jsonObj.getString("townName"); - if (!jsonObj.isNull("point")) { - locust.lon_center = String.valueOf(jsonObj.getJSONObject("point").getJSONArray("coordinates").getDouble(0)); - locust.lat_center = String.valueOf(jsonObj.getJSONObject("point").getJSONArray("coordinates").getDouble(1)); - } - - //Контур зоны распространения ВО Polygon (geoJSON) - locust.drawPolygon = null; - if (!jsonObj.isNull("drawPolygon")) { - locust.drawPolygon = jsonObj.getJSONObject("drawPolygon").toString(); - } - - //Площадь контура зоны распространения, в случае если специалист указал его - locust.size = "null"; - if (!jsonObj.isNull("polygonArea")) - locust.size = String.valueOf(jsonObj.getDouble("polygonArea")); - - //jsonObj.drawPolygon Краснодар - - if (regionName.isEmpty()) { - //Выбираю ID области - locust.region_id = ""; - //Statement stt = null; - //ResultSet rs = null; - try { - - stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - String sql_query = "select id from main.countriesregions where name like '%" + regionName + "%';"; - rs = stt.executeQuery(sql_query); - if (rs != null) { - try { - if (rs.next()) { - locust.region_id = rs.getString(1); - } - rs.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - } - } catch (SQLException ex) { - ex.printStackTrace(); - } finally { - if (rs != null) try { - rs.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - } - if (stt != null) try { - stt.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - } + if (!jsonObj.isNull("point")) { + locust.lon_center = String.valueOf(jsonObj.getJSONObject("point").getJSONArray("coordinates").getDouble(0)); + locust.lat_center = String.valueOf(jsonObj.getJSONObject("point").getJSONArray("coordinates").getDouble(1)); } - - /*if(locust.region_id.isEmpty()){ - if(regionName.indexOf("Воронежс��ая область")>=0) locust.region_id="110"; - if(regionName.indexOf("Кра��нодарский край")>=0) locust.region_id="164"; - if(regionName.indexOf("Астраха��ская область")>=0) locust.region_id="68"; //dayOfYear: 97 at year: 2022 = 07.04.2022 - if(regionName.indexOf("Астраханская област��")>=0) locust.region_id="68"; // dayOfYear: 101 at year: 2022 = 11.04.2022 - }*/ + //Контур зоны распространения ВО Polygon (geoJSON) + locust.drawPolygon = null; + if (!jsonObj.isNull("drawPolygon")) { + locust.drawPolygon = jsonObj.getJSONObject("drawPolygon").toString(); + } - if (locust.region_id.length() > 0) { - //Выбираю id региона (main.countriesdistricts) - locust.district_id = ""; - stt = null; - rs = null; + //Площадь контура зоны распространения, в случае если специалист указал его + locust.size = "null"; + if (!jsonObj.isNull("polygonArea")) + locust.size = String.valueOf(jsonObj.getDouble("polygonArea")); + + //jsonObj.drawPolygon Краснодар + + if (!regionName.isEmpty()) { + //Выбираю ID области + locust.region_id = ""; + //Statement stt = null; + //ResultSet rs = null; try { - if (locust.district.equals("Алапаевский район")) - locust.district = "городской округ Алапаевское"; - if (locust.district.equals("Сухоложский район")) - locust.district = "городской округ Сухой Лог"; - if (locust.district.equals("Талицкий район")) - locust.district = "Талицкий городской округ"; - if (locust.district.equals("Артинский район")) - locust.district = "Талицкий городской округ"; - if (locust.district.equals("Богдановичский район")) - locust.district = "городской округ Богданович"; - if (locust.district.equals("Красноуфимский район")) - locust.district = "Красноуфимский округ"; - if (locust.district.equals("Белоярский район")) locust.region_id = "210"; - if (locust.district.equals("Пышминский район")) - locust.district = "Пышминский городской округ"; - if (locust.district.equals("Ирбитский район")) - locust.district = "городской округ Ирбитское"; - if (locust.district.equals("Фрязино г.о.")) locust.district = "городской округ Фрязино"; - if (locust.district.equals("Коломенский г.о.")) locust.district = "Коломенский район"; - if (locust.district.equals("Протвино г.о.")) - locust.district = "городской округ Протвино"; - if (locust.district.equals("Зарайск г.о.")) locust.district = "Зарайский район"; - if (locust.district.equals("Анапский район")) locust.district = "городской округ Анапа"; - if (locust.district.equals("Луховицы г.о.")) locust.district = "Луховицкий район"; - if (locust.district.equals("Дергачевский район")) - locust.district = "Дергачёвский район"; - if (locust.district.equals("Чистоозерный район")) - locust.district = "Чистоозёрный район"; - if (locust.district.equals("Сунжа город")) locust.district = "Сунженский район"; - if (locust.district.equals("Буденновский район")) - locust.district = "Будённовский район"; - if (locust.district.equals("Новоселовский район")) { - locust.district = "Новоселицкий район"; - locust.region_id = "168"; - } - if (locust.district.equals("Тимашевский район")) locust.district = "Тимашёвский район"; - if (locust.district.equals("Славгородский район")) - locust.district = "городской округ Славгород"; - if (locust.district.equals("Режевский район")) - locust.district = "Режевской городской округ"; - if (locust.district.equals("Веселовский район")) locust.district = "Весёловский район"; - if (locust.district.equals("Карабулак город")) - locust.district = "городской округ Карабулак"; - if (locust.district.equals("Пугачевский район")) locust.district = "Пугачёвский район"; - if (locust.district.equals("Кущевский район")) locust.district = "Кущёвский район"; - if (locust.district.equals("Репьевский район")) locust.district = "Репьёвский район"; - if (locust.district.equals("Калачевский район")) locust.district = "Калачёвский район"; - if (locust.district.equals("Гайский район")) - locust.district = "Гайский городской округ"; - if (locust.district.equals("Новохоперский район")) - locust.district = "Новохопёрский район"; - if (locust.district.equals("Федоровский район")) locust.district = "Фёдоровский район"; - if (locust.district.equals("Серебряные Пруды г.о.")) - locust.district = "городской округ Серебряные Пруды"; - if (locust.district.equals("Минераловодский район")) - locust.district = "Минераловодский городской округ"; - if (locust.district.equals("Рузский г.о.")) locust.district = "Рузский район"; - if (locust.district.equals("Воробьевский район")) - locust.district = "Воробьёвский район"; - if (locust.district.equals("Ачитский район")) - locust.district = "Ачитский городской округ"; - if (locust.district.equals("Грачевский район")) locust.district = "Грачёвский район"; - if (locust.district.equals("Уссурийский район")) - locust.district = "Уссурийский городской округ"; - if (locust.district.equals("Сорочинский район")) - locust.district = "Сорочинский городской округ"; - if (locust.district.equals("Ясненский район")) - locust.district = "Ясненский городской округ"; - stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); - String sql_query = "select id from main.countriesdistricts where region_id=" + locust.region_id + " and name like '%" + locust.district + "%';"; + String sql_query = "select id from main.countriesregions where name like '%" + regionName + "%';"; rs = stt.executeQuery(sql_query); if (rs != null) { try { if (rs.next()) { - locust.district_id = rs.getString(1); + locust.region_id = rs.getString(1); } rs.close(); } catch (SQLException ex) { - ex.printStackTrace(); + throw new CustomException(200, 10000, ex.getMessage(),null,true); } } } catch (SQLException ex) { - ex.printStackTrace(); + throw new CustomException(200, 10000, ex.getMessage(),null,true); } finally { if (rs != null) try { rs.close(); } catch (SQLException ex) { - ex.printStackTrace(); + throw new CustomException(200, 10000, ex.getMessage(),null,true); } if (stt != null) try { stt.close(); } catch (SQLException ex) { - ex.printStackTrace(); + throw new CustomException(200, 10000, ex.getMessage(),null,true); } } - } - } - String row = ""; - if (!jsonObj.isNull("subjectList")) { - JSONArray jsonArraySub = jsonObj.getJSONArray("subjectList"); + /*if(locust.region_id.isEmpty()){ + if(regionName.indexOf("Воронежс��ая область")>=0) locust.region_id="110"; + if(regionName.indexOf("Кра��нодарский край")>=0) locust.region_id="164"; + if(regionName.indexOf("Астраха��ская область")>=0) locust.region_id="68"; //dayOfYear: 97 at year: 2022 = 07.04.2022 + if(regionName.indexOf("Астраханская област��")>=0) locust.region_id="68"; // dayOfYear: 101 at year: 2022 = 11.04.2022 + }*/ - for (Object o2 : jsonArraySub) { - JSONObject jsonObjSub = (JSONObject) o2; - - locust.eid = String.valueOf(jsonObjSub.getInt("id")); - locust.phytoType = jsonObjSub.getString("phytoType"); //"Вредители" или "Обработка" - if (locust.phytoType.equals("Обработка")) { - locust.insecticide_name = jsonObjSub.getString("nameSubject"); //Наименование действующего вещества - if (!jsonObjSub.isNull("nameLatSubject")) - locust.insecticide_active_substance = jsonObjSub.getString("nameLatSubject"); //Латинское наименование действующего вещества - if (!jsonObjSub.isNull("protectionDoze")) - locust.insecticide_dose = String.valueOf(jsonObjSub.getFloat("protectionDoze")); //Доза внесения препарата (л/га) - - if (!jsonObjSub.isNull("agroTreatmentType")) { - String agroTreatmentType = jsonObjSub.getString("agroTreatmentType"); //Тип обработки (Агротехнический, Авиационный, Наземный) - if (agroTreatmentType != null && !agroTreatmentType.isEmpty()) { - if (agroTreatmentType.equals("GROUND")) { - locust.spray_platform = "3"; - } else if (agroTreatmentType.equals("AGROTECHNICAL")) { - locust.spray_platform = "5"; - } else if (agroTreatmentType.equals("AVIATION")) { - locust.spray_platform = "1"; - } - } - if (locust.spray_platform == null || locust.spray_platform.isEmpty()) { - model.addAttribute("PreviewTable", "Error spray_platform"); - return "json"; - } - } - - //То что не знаю куда записывать записываю в description - locust.description = ""; - if (!jsonObjSub.isNull("agroTreatmentPercentage")) - locust.description += "Процент обработанной площади: " + String.valueOf(jsonObjSub.getFloat("agroTreatmentPercentage")) + "\n"; - if (!jsonObjSub.isNull("agroTreatmentPow")) - locust.description += "Степень обработки: " + jsonObjSub.getString("agroTreatmentPow") + "\n"; - - //Если записи не существует то вставляем если существует то обновляем - boolean exists = false; //Is there a record. - Statement st; + if (locust.region_id.length() > 0) { + //Выбираю id региона (main.countriesdistricts) + locust.district_id = ""; + stt = null; + rs = null; try { - st = conn.createStatement(); - //ResultSet rs=null; - try { - String sql = "select 1 from main.frmlocustdel where eid=" + String.valueOf(locust.eid); - rs = st.executeQuery(sql); - } catch (SQLException ex) { - ex.printStackTrace(); - model.addAttribute("PreviewTable", "Error select"); - return "json"; + + if (locust.district.equals("Алапаевский район")) + locust.district = "городской округ Алапаевское"; + if (locust.district.equals("Сухоложский район")) + locust.district = "городской округ Сухой Лог"; + if (locust.district.equals("Талицкий район")) + locust.district = "Талицкий городской округ"; + if (locust.district.equals("Артинский район")) + locust.district = "Талицкий городской округ"; + if (locust.district.equals("Богдановичский район")) + locust.district = "городской округ Богданович"; + if (locust.district.equals("Красноуфимский район")) + locust.district = "Красноуфимский округ"; + if (locust.district.equals("Белоярский район")) locust.region_id = "210"; + if (locust.district.equals("Пышминский район")) + locust.district = "Пышминский городской округ"; + if (locust.district.equals("Ирбитский район")) + locust.district = "городской округ Ирбитское"; + if (locust.district.equals("Фрязино г.о.")) locust.district = "городской округ Фрязино"; + if (locust.district.equals("Коломенский г.о.")) locust.district = "Коломенский район"; + if (locust.district.equals("Протвино г.о.")) + locust.district = "городской округ Протвино"; + if (locust.district.equals("Зарайск г.о.")) locust.district = "Зарайский район"; + if (locust.district.equals("Анапский район")) locust.district = "городской округ Анапа"; + if (locust.district.equals("Луховицы г.о.")) locust.district = "Луховицкий район"; + if (locust.district.equals("Дергачевский район")) + locust.district = "Дергачёвский район"; + if (locust.district.equals("Чистоозерный район")) + locust.district = "Чистоозёрный район"; + if (locust.district.equals("Сунжа город")) locust.district = "Сунженский район"; + if (locust.district.equals("Буденновский район")) + locust.district = "Будённовский район"; + if (locust.district.equals("Новоселовский район")) { + locust.district = "Новоселицкий район"; + locust.region_id = "168"; } + if (locust.district.equals("Тимашевский район")) locust.district = "Тимашёвский район"; + if (locust.district.equals("Славгородский район")) + locust.district = "городской округ Славгород"; + if (locust.district.equals("Режевский район")) + locust.district = "Режевской городской округ"; + if (locust.district.equals("Веселовский район")) locust.district = "Весёловский район"; + if (locust.district.equals("Карабулак город")) + locust.district = "городской округ Карабулак"; + if (locust.district.equals("Пугачевский район")) locust.district = "Пугачёвский район"; + if (locust.district.equals("Кущевский район")) locust.district = "Кущёвский район"; + if (locust.district.equals("Репьевский район")) locust.district = "Репьёвский район"; + if (locust.district.equals("Калачевский район")) locust.district = "Калачёвский район"; + if (locust.district.equals("Гайский район")) + locust.district = "Гайский городской округ"; + if (locust.district.equals("Новохоперский район")) + locust.district = "Новохопёрский район"; + if (locust.district.equals("Федоровский район")) locust.district = "Фёдоровский район"; + if (locust.district.equals("Серебряные Пруды г.о.")) + locust.district = "городской округ Серебряные Пруды"; + if (locust.district.equals("Минераловодский район")) + locust.district = "Минераловодский городской округ"; + if (locust.district.equals("Рузский г.о.")) locust.district = "Рузский район"; + if (locust.district.equals("Воробьевский район")) + locust.district = "Воробьёвский район"; + if (locust.district.equals("Ачитский район")) + locust.district = "Ачитский городской округ"; + if (locust.district.equals("Грачевский район")) locust.district = "Грачёвский район"; + if (locust.district.equals("Уссурийский район")) + locust.district = "Уссурийский городской округ"; + if (locust.district.equals("Сорочинский район")) + locust.district = "Сорочинский городской округ"; + if (locust.district.equals("Ясненский район")) + locust.district = "Ясненский городской округ"; + if (locust.district.equals("Белогорский муниципальный округ")) { + locust.district = "городской округ Белгород"; + locust.region_id = "69"; + } + + stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + String sql_query = "select id from main.countriesdistricts where region_id=" + locust.region_id + " and name like '%" + locust.district + "%';"; + rs = stt.executeQuery(sql_query); if (rs != null) { - if (rs.next()) - exists = true; - } - st.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - model.addAttribute("PreviewTable", "Error select 2"); - return "json"; - } - - PreparedStatement stmt = null; - String sql = ""; - if (exists) { - System.out.println(String.valueOf(cntV)+") update main.frmlocustdel"); - sql = "update main.frmlocustdel set\n" - + " eid=?,\n" - + " lat_center=?,\n" - + " lon_center=?,\n" - + " country_id=?,\n" - + " region_id=?,\n" - + " area=?,\n" - + " district=?,\n" - + " date=TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" - + " description=?,\n" - + " geom=ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" - - + " insecticide_name=?,\n" - + " insecticide_active_substance=?,\n" - + " insecticide_dose=?,\n" - + " spray_platform=?\n" - + " where eid='" + locust.eid + "'"; - try { - stmt = conn.prepareStatement(sql); - } catch (SQLException ex) { - ex.printStackTrace(); - model.addAttribute("PreviewTable", "Error prepare 1"); - return "json"; - } - } else { - System.out.println(String.valueOf(cntV)+") insert into main.frmlocustdel"); - sql = "insert into main.frmlocustdel(\n" - + " eid,\n" //1 - + " lat_center,\n" //2 - + " lon_center,\n" //3 - + " country_id,\n" //4 - + " region_id,\n" //5 - + " area,\n" //6 - + " district,\n" //7 - + " date,\n" //8 - + " description,\n" //9 - + " geom,\n" //10 - - + " insecticide_name,\n" //11 - + " insecticide_active_substance,\n" //12 - + " insecticide_dose,\n" //13 - + " spray_platform\n" //14 - - + ")values(\n" - + " ?,\n" //1 eid - + " ?,\n" //2 lat1 - + " ?,\n" //3 lon1 - + " ?,\n" //4 country_id - + " ?,\n" //5 region_id - + " ?,\n" //6 district (area) - + " ?,\n" //7 district (area) - + " TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" //8 date - + " ?,\n" //9 description - + " ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" //10 geom - - + " ?,\n" //11 insecticide_name - + " ?,\n" //12 insecticide_active_substance - + " ?,\n" //13 insecticide_dose - + " ?\n" //14 spray_platform - + ")"; - try { - stmt = conn.prepareStatement(sql); - } catch (SQLException ex) { - ex.printStackTrace(); - model.addAttribute("PreviewTable", "Error prepare 2"); - return "json"; - } - } - - try { - if (locust.eid == null) stmt.setNull(1, Types.INTEGER); else stmt.setLong(1, Long.parseLong(locust.eid)); - if (locust.lat_center == null) stmt.setNull(2, Types.DOUBLE); else stmt.setDouble(2, Double.parseDouble(locust.lat_center)); - if (locust.lon_center == null) stmt.setNull(3, Types.DOUBLE); else stmt.setDouble(3, Double.parseDouble(locust.lon_center)); - stmt.setInt(4, 7); //country_id - stmt.setInt(5, Integer.parseInt(locust.region_id)); //region_id - stmt.setString(6, locust.district); //Пишу в поле "area" - stmt.setString(7, null); - stmt.setString(8, locust.date); //27.04.2020 09:17 - stmt.setString(9, locust.description); - stmt.setString(10, locust.drawPolygon); - - stmt.setString(11, locust.insecticide_name); - stmt.setString(12, locust.insecticide_active_substance); - if (locust.insecticide_dose == null || locust.insecticide_dose.isEmpty()) - stmt.setNull(13, Types.DOUBLE); - else - stmt.setDouble(13, Double.parseDouble(locust.insecticide_dose)); - - if (locust.spray_platform == null || locust.spray_platform.isEmpty()) - stmt.setNull(14, Types.INTEGER); - else - stmt.setInt(14, Integer.parseInt(locust.spray_platform)); - - } catch (SQLException ex) { - ex.printStackTrace(); - model.addAttribute("PreviewTable", "Error set data"); - return "json"; - } - - //Выпоняю запрос на свтавку либо обновление - try { - stmt.execute(); - } catch (SQLException ex) { - ex.printStackTrace(); - model.addAttribute("PreviewTable", "Error execute frmlocustdel"); - return "json"; - } - cntO++; - - } else if (locust.phytoType.equals("Вредители")) { - if (!jsonObjSub.isNull("nameSubject")) - locust.locust = jsonObjSub.getString("nameSubject"); - - //Вид саранчи - locust.locust_type_id = ""; - if (locust.locust.equals("Короткокрылый зеленчук")) locust.locust_type_id = "4"; - if (locust.locust.equals("Среднерусская перелётная саранча")) locust.locust_type_id = "4"; - if (locust.locust.equals("Сибирская кобылка")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка изменчивая")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка пёстрая")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка крестовая")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка сибирская")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка голубокрылая")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка бескрылая")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка чернополосая")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка трескучая")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка египетская")) locust.locust_type_id = "4"; - if (locust.locust.equals("Трещотка ширококрылая")) locust.locust_type_id = "4"; - if (locust.locust.equals("Бахчевая кобылка")) locust.locust_type_id = "4"; - if (locust.locust.equals("Малая крестовичка")) locust.locust_type_id = "4"; - if (locust.locust.equals("Конёк белополосый (белополосая кобылка)")) - locust.locust_type_id = "4"; - if (locust.locust.equals("Конек обыкновенный")) locust.locust_type_id = "4"; - if (locust.locust.equals("Конек обыкновенный")) locust.locust_type_id = "4"; - if (locust.locust.equals("Кобылка темнокрылая")) locust.locust_type_id = "4"; - if (locust.locust.equals("Краснокрылая кобылка")) locust.locust_type_id = "4"; - if (locust.locust.equals("Краснокрылая кобылка")) locust.locust_type_id = "4"; - if (locust.locust.equals("Степная кобылка")) locust.locust_type_id = "4"; - if (locust.locust.equals("Гребневка")) locust.locust_type_id = "4"; - if (locust.locust.equals("Азиатская перелётная саранча")) locust.locust_type_id = "3"; - if (locust.locust.equals("Итальянский прус")) locust.locust_type_id = "1"; - if (locust.locust.equals("Мароккская саранча, мароккская кобылка, марокканка")) - locust.locust_type_id = "2"; - - //фаза саранчи - if (!jsonObjSub.isNull("phaseEvolutionName")) - locust.phase = jsonObjSub.getString("phaseEvolutionName"); - - locust.locust_have = "3"; - if (locust.phase != null) { - if (locust.phase.equals("Кубышка")) locust.locust_have = "2"; //Кубышка = Яйца - if (locust.phase.equals("Гусеница")) locust.locust_have = "3"; - if (locust.phase.equals("Личинка 2-го возраста")) locust.locust_have = "3"; - if (locust.phase.equals("Личинка 3-го возраста")) locust.locust_have = "3"; - if (locust.phase.equals("Личинка 4-го возраста")) locust.locust_have = "3"; - if (locust.phase.equals("Личинка 5-го возраста")) locust.locust_have = "3"; - if (locust.phase.equals("Имаго")) locust.locust_have = "5"; - } - //Если эта анкета "Имаго" то записываем плотность имаго на m2 - if (locust.locust_have.equals("5")) { - if (!jsonObjSub.isNull("subPestCount")) - locust.imago_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); - } - //Если эта анкета "Кубышка"="Яйца" то записываем плотность кулиг на m2 - if (locust.locust_have.equals("2")) { - if (!jsonObjSub.isNull("subPestCount")) - locust.eggs_capsules_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); - } - //Если эта анкета "Кулиги" то записываем плотность кулиг на m2 - if (locust.locust_have.equals("4")) { - if (!jsonObjSub.isNull("subPestCount")) - locust.kuliguli_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); - } - //Если эта анкета "Личинок" то записываем плотность личинок на m2 - if (locust.locust_have.equals("3")) { - if (!jsonObjSub.isNull("subPestCount")) - locust.larva_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); - } - - //Биотоп - switch (jsonObjSub.getString("faoBiotopeName")) { - case "CIT степь": - locust.bio_biotope_id = "1"; - break; - case "CIT залежь": - locust.bio_biotope_id = "2"; - break; - case "CIT посевы": - locust.bio_biotope_id = "3"; - break; - case "CIT пастбища": - locust.bio_biotope_id = "11"; - break; - case "CIT холмы, горы": - locust.bio_biotope_id = "19"; - break; - case "DMA равнины": - locust.bio_biotope_id = "4"; - break; - case "DMA посевы": - locust.bio_biotope_id = "6"; - break; - case "DMA пастбища": - locust.bio_biotope_id = "13"; - break; - case "DMA холмы, горы": - locust.bio_biotope_id = "14"; - break; - case "LMI низкие сухие тростники": - locust.bio_biotope_id = "7"; - break; - case "LMI высокие влажные тростники": - locust.bio_biotope_id = "8"; - break; - case "LMI другое": - locust.bio_biotope_id = "10"; - break; - case "Другие саранчовые на посевах": - locust.bio_biotope_id = "15"; - break; - case "Другие саранчовые на равнине": - locust.bio_biotope_id = "16"; - break; - case "Другие саранчовые на холмах": - locust.bio_biotope_id = "17"; - break; - case "Другое": - locust.bio_biotope_id = "18"; - break; - default: - locust.bio_biotope_id = null; - break; - } - - //Если те виды что нам нужны - if (regionName == null || regionName.isEmpty() || Double.parseDouble(locust.lat_center) == 0 || Double.parseDouble(locust.lon_center) == 0 || locust.locust.equals("Совка ипсилон") || locust.locust.equals("Восточный майский хрущ") || locust.locust.equals("Кукурузный стеблевой мотылек") || locust.locust.equals("Картофельная, или болотная совка, лиловатая яровая совка") || locust.locust.equals("Луговой мотылёк") || locust.locust.equals("Хлопковая совка") || locust.locust.equals("Стеблевой кукурузный мотылек") || locust.locust.equals("Восточная луговая совка") || locust.locust.equals("Коричневая щитовка") || locust.locust.equals("Продолговатая (чайная) подушечница") || locust.locust.equals("Яблоневая запятовидная щитовка") || locust.locust.equals("Виноградная филлоксера") || locust.locust.equals("Бахчевая коровка")) { - - } else { - - if (locust.locust_type_id.isEmpty()) { - System.out.println("locust.locust = "+locust.locust); - model.addAttribute("PreviewTable", "locust.locust_type_id == 0 locust name = " + locust.locust); - logger.error("Error, not find locust.locust = "+locust.locust); - return "json"; - } - if (locust.region_id.isEmpty()) { - System.out.println("locust.region = "+regionName); - model.addAttribute("PreviewTable", "locust.region_id == 0 region name = " + regionName); - logger.error("Error, not find locust.region = "+regionName); - return "json"; - } - - //Тех полей что нет в анкете вствляю в комментарии - try { - locust.description = ""; - - if (jsonObjSub.getBoolean("notFound")) - locust.description += "Вредитель не обнаружен: " + jsonObjSub.getString("nameSubject") + "\n"; - else - locust.description += "Вредитель обнаружен: " + jsonObjSub.getString("nameSubject") + "\n"; - - if (!jsonObjSub.isNull("phaseEvolutionName")) - locust.description += "Фаза: " + jsonObjSub.getString("phaseEvolutionName") + "\n"; //Так как фаза у росиян более подробная - if (!jsonObjSub.isNull("subPestCount")) { - locust.description += "Вредителей: " + jsonObjSub.getFloat("subPestCount"); - if (!jsonObjSub.isNull("unitName")) - locust.description += " " + jsonObjSub.getString("unitName"); - locust.description += "\n"; + try { + if (rs.next()) { + locust.district_id = rs.getString(1); + } + rs.close(); + } catch (SQLException ex) { + throw new CustomException(200, 10000, ex.getMessage(),null,true); } + } + } catch (SQLException ex) { + throw new CustomException(200, 10000, ex.getMessage(),null,true); + } finally { + if (rs != null) try { + rs.close(); + } catch (SQLException ex) { + throw new CustomException(200, 10000, ex.getMessage(),null,true); + } + if (stt != null) try { + stt.close(); + } catch (SQLException ex) { + throw new CustomException(200, 10000, ex.getMessage(),null,true); + } + } + } + }else{ + throw new CustomException(200, 10000, "regionName.isEmpty()",null,true); + } - if (!jsonObj.isNull("cropCurrentType")) - locust.description += "Тип сева: " + jsonObj.getString("cropCurrentType") + "\n"; - if (!jsonObj.isNull("cropCurrentCulture")) - locust.description += "Наименование культуры: " + jsonObj.getString("cropCurrentCulture") + "\n"; - if (!jsonObj.isNull("cropCurrentCultureSort")) - locust.description += "Наименование сорта культуры: " + jsonObj.getString("cropCurrentCultureSort") + "\n"; - if (!jsonObj.isNull("cropCurrentGrowthPhase")) - locust.description += "Фаза роста культуры: " + jsonObj.getString("cropCurrentGrowthPhase") + "\n"; - if (!jsonObj.isNull("cropFieldArea")) { - locust.description += "Площадь поля: " + jsonObj.getFloat("cropFieldArea") + "\n"; - locust.bio_hectare = String.valueOf(jsonObj.getFloat("cropFieldArea")); + String row = ""; + + if (!jsonObj.isNull("subjectList")) { + JSONArray jsonArraySub = jsonObj.getJSONArray("subjectList"); + + for (Object o2 : jsonArraySub) { + JSONObject jsonObjSub = (JSONObject) o2; + + locust.eid = String.valueOf(jsonObjSub.getInt("id")); + locust.phytoType = jsonObjSub.getString("phytoType"); //"Вредители" или "Обработка" + if (locust.phytoType.equals("Обработка")) { + locust.insecticide_name = jsonObjSub.getString("nameSubject"); //Наименование действующего вещества + if (!jsonObjSub.isNull("nameLatSubject")) + locust.insecticide_active_substance = jsonObjSub.getString("nameLatSubject"); //Латинское наименование действующего вещества + if (!jsonObjSub.isNull("protectionDoze")) + locust.insecticide_dose = String.valueOf(jsonObjSub.getFloat("protectionDoze")); //Доза внесения препарата (л/га) + + if (!jsonObjSub.isNull("agroTreatmentType")) { + String agroTreatmentType = jsonObjSub.getString("agroTreatmentType"); //Тип обработки (Агротехнический, Авиационный, Наземный) + if (agroTreatmentType != null && !agroTreatmentType.isEmpty()) { + if (agroTreatmentType.equals("GROUND")) { + locust.spray_platform = "3"; + } else if (agroTreatmentType.equals("AGROTECHNICAL")) { + locust.spray_platform = "5"; + } else if (agroTreatmentType.equals("AVIATION")) { + locust.spray_platform = "1"; + } + } + if (locust.spray_platform == null || locust.spray_platform.isEmpty()) { + model.addAttribute("PreviewTable", "Error spray_platform"); + throw new CustomException(200, 10000, "Error spray_platform",null,true); } - - - } catch (Exception ex) { - ex.printStackTrace(); } - locust.terrain = "null"; //У росиян нет сельского округа - - row = ""; - if (locust.region_id == null || locust.region_id.isEmpty() || locust.district_id == null || locust.district_id.isEmpty() || locust.locust_type_id == null || locust.locust_type_id.isEmpty()) { - row = ""; - } - row += ""; - row += "\n"; + //То что не знаю куда записывать записываю в description + locust.description = ""; + if (!jsonObjSub.isNull("agroTreatmentPercentage")) + locust.description += "Процент обработанной площади: " + String.valueOf(jsonObjSub.getFloat("agroTreatmentPercentage")) + "\n"; + if (!jsonObjSub.isNull("agroTreatmentPow")) + locust.description += "Степень обработки: " + jsonObjSub.getString("agroTreatmentPow") + "\n"; //Если записи не существует то вставляем если существует то обновляем boolean exists = false; //Is there a record. @@ -1088,12 +809,12 @@ public class AcceptJSON implements ServletContextAware { st = conn.createStatement(); //ResultSet rs=null; try { - String sql = "select 1 from main.frmlocust where eid=" + String.valueOf(locust.eid); + sql = "select 1 from main.frmlocustdel where eid=" + String.valueOf(locust.eid); rs = st.executeQuery(sql); } catch (SQLException ex) { ex.printStackTrace(); model.addAttribute("PreviewTable", "Error select"); - return "json"; + throw new CustomException(200, 10000, ex.getMessage(),null,true); } if (rs != null) { if (rs.next()) @@ -1103,14 +824,14 @@ public class AcceptJSON implements ServletContextAware { } catch (SQLException ex) { ex.printStackTrace(); model.addAttribute("PreviewTable", "Error select 2"); - return "json"; + throw new CustomException(200, 10000, ex.getMessage(),null,true); } PreparedStatement stmt = null; - String sql = ""; + sql = ""; if (exists) { - System.out.println(String.valueOf(cntV)+") update main.frmlocust"); - sql = "update main.frmlocust set\n" + System.out.println(String.valueOf(cntV)+") update main.frmlocustdel"); + sql = "update main.frmlocustdel set\n" + " eid=?,\n" + " lat_center=?,\n" + " lon_center=?,\n" @@ -1121,24 +842,22 @@ public class AcceptJSON implements ServletContextAware { + " date=TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" + " description=?,\n" + " geom=ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" - + " locust_type_id=?,\n" - + " imago_density=?,\n" - + " kuliguli_density=?,\n" - + " larva_density=?,\n" - + " bio_hectare=?\n," - + " eggs_capsules_density=?,\n" - + " bio_biotope_id=?\n" + + + " insecticide_name=?,\n" + + " insecticide_active_substance=?,\n" + + " insecticide_dose=?,\n" + + " spray_platform=?\n" + " where eid='" + locust.eid + "'"; try { stmt = conn.prepareStatement(sql); } catch (SQLException ex) { ex.printStackTrace(); model.addAttribute("PreviewTable", "Error prepare 1"); - return "json"; + throw new CustomException(200, 10000, ex.getMessage(),null,true); } } else { - System.out.println(String.valueOf(cntV)+") insert into main.frmlocust"); - sql = "insert into main.frmlocust(\n" + System.out.println(String.valueOf(cntV)+") insert into main.frmlocustdel"); + sql = "insert into main.frmlocustdel(\n" + " eid,\n" //1 + " lat_center,\n" //2 + " lon_center,\n" //3 @@ -1149,13 +868,12 @@ public class AcceptJSON implements ServletContextAware { + " date,\n" //8 + " description,\n" //9 + " geom,\n" //10 - + " locust_type_id,\n" //11 - + " imago_density,\n" //12 - + " kuliguli_density,\n" //13 - + " larva_density,\n" //14 - + " bio_hectare,\n" //15 - + " eggs_capsules_density,\n" //16 - + " bio_biotope_id\n" //17 + + + " insecticide_name,\n" //11 + + " insecticide_active_substance,\n" //12 + + " insecticide_dose,\n" //13 + + " spray_platform\n" //14 + + ")values(\n" + " ?,\n" //1 eid + " ?,\n" //2 lat1 @@ -1167,234 +885,565 @@ public class AcceptJSON implements ServletContextAware { + " TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" //8 date + " ?,\n" //9 description + " ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" //10 geom - + " ?,\n" //11 locust_type_id - + " ?,\n" //12 imago_density - + " ?,\n" //13 kuliguli_density - + " ?,\n" //14 larva_density - + " ?,\n" //15 - + " ?,\n" //16 - + " ?\n" //17 + + + " ?,\n" //11 insecticide_name + + " ?,\n" //12 insecticide_active_substance + + " ?,\n" //13 insecticide_dose + + " ?\n" //14 spray_platform + ")"; try { stmt = conn.prepareStatement(sql); } catch (SQLException ex) { ex.printStackTrace(); model.addAttribute("PreviewTable", "Error prepare 2"); - return "json"; + throw new CustomException(200, 10000, ex.getMessage(),null,true); } } try { - stmt.setLong(1, Long.parseLong(locust.eid)); - stmt.setDouble(2, Double.parseDouble(locust.lat_center)); - stmt.setDouble(3, Double.parseDouble(locust.lon_center)); - stmt.setInt(4, 7); - stmt.setInt(5, Integer.parseInt(locust.region_id)); + if (locust.eid == null) stmt.setNull(1, Types.INTEGER); else stmt.setLong(1, Long.parseLong(locust.eid)); + if (locust.lat_center == null) stmt.setNull(2, Types.DOUBLE); else stmt.setDouble(2, Double.parseDouble(locust.lat_center)); + if (locust.lon_center == null) stmt.setNull(3, Types.DOUBLE); else stmt.setDouble(3, Double.parseDouble(locust.lon_center)); + stmt.setInt(4, 7); //country_id + stmt.setInt(5, Integer.parseInt(locust.region_id)); //region_id stmt.setString(6, locust.district); //Пишу в поле "area" stmt.setString(7, null); stmt.setString(8, locust.date); //27.04.2020 09:17 stmt.setString(9, locust.description); stmt.setString(10, locust.drawPolygon); - stmt.setInt(11, Integer.parseInt(locust.locust_type_id)); - if (locust.imago_density != null) - stmt.setFloat(12, Float.parseFloat(locust.imago_density)); + + stmt.setString(11, locust.insecticide_name); + stmt.setString(12, locust.insecticide_active_substance); + if (locust.insecticide_dose == null || locust.insecticide_dose.isEmpty()) + stmt.setNull(13, Types.DOUBLE); else - stmt.setNull(12, Types.FLOAT); - if (locust.kuliguli_density != null) - stmt.setFloat(13, Float.parseFloat(locust.kuliguli_density)); + stmt.setDouble(13, Double.parseDouble(locust.insecticide_dose)); + + if (locust.spray_platform == null || locust.spray_platform.isEmpty()) + stmt.setNull(14, Types.INTEGER); else - stmt.setNull(13, Types.FLOAT); - if (locust.larva_density != null) - stmt.setFloat(14, Float.parseFloat(locust.larva_density)); - else - stmt.setNull(14, Types.FLOAT); - if (locust.bio_hectare != null) - stmt.setFloat(15, Float.parseFloat(locust.bio_hectare)); - else - stmt.setNull(15, Types.FLOAT); - if (locust.eggs_capsules_density != null) - stmt.setFloat(16, Float.parseFloat(locust.eggs_capsules_density)); - else - stmt.setNull(16, Types.FLOAT); - if (locust.bio_biotope_id != null) - stmt.setFloat(17, Float.parseFloat(locust.bio_biotope_id)); - else - stmt.setNull(17, Types.INTEGER); + stmt.setInt(14, Integer.parseInt(locust.spray_platform)); } catch (SQLException ex) { ex.printStackTrace(); model.addAttribute("PreviewTable", "Error set data"); - return "json"; + + throw new CustomException(200, 10000, ex.getMessage(),null,true); } + //Выпоняю запрос на свтавку либо обновление try { stmt.execute(); } catch (SQLException ex) { ex.printStackTrace(); - model.addAttribute("PreviewTable", "Error execute 0"); - return "json"; - } - cntV++; + model.addAttribute("PreviewTable", "Error execute frmlocustdel"); - //Скачиваю фотографию для анкеты - sb = new StringBuilder(); - try { - String strURL = "https://rscagex.ru/pmon/rest/getPhotosByParentId?token=QVOUE97HBSI6LBSGJGQZMP3KPSS1QK&parentId=" + locust.eid; - URL url = new URL(strURL); - HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); - hConn.setRequestMethod("GET"); - //hConn.setRequestProperty("Range","bytes=" + posStart + "-" + posEnd); - hConn.connect(); - int responseCode = hConn.getResponseCode(); - if (responseCode / 100 == 2) //Code 206 is "Partial Content" - { - InputStream inputStream = hConn.getInputStream(); - //FileOutputStream outputStream = new FileOutputStream(strFile); - int bytesRead; - byte[] buffer = new byte[BUFFER_SIZE]; - while ((bytesRead = inputStream.read(buffer)) != -1) { - //outputStream.write(buffer, 0, bytesRead); - sb.append(new String(buffer, 0, bytesRead)); - } - //outputStream.close(); - inputStream.close(); + throw new CustomException(200, 10000, ex.getMessage(),null,true); + } + cntO++; + + } else if (locust.phytoType.equals("Вредители")) { + //Вид саранчи + locust.locust_type_id = ""; + + if(!jsonObjSub.isNull("nameSubject") && !jsonObjSub.optString("nameSubject","").isBlank()) { + locust.locust = jsonObjSub.getString("nameSubject"); + switch (jsonObjSub.optString("nameSubject",null).replace("'", "").trim()) { + case "Короткокрылый зеленчук", "Среднерусская перелётная саранча", "Сибирская кобылка", "Кобылка изменчивая", "Кобылка пёстрая", "Кобылка крестовая", "Кобылка сибирская", "Кобылка голубокрылая", "Кобылка бескрылая", "Кобылка чернополосая", "Кобылка трескучая", "Кобылка египетская", "Трещотка ширококрылая", "Бахчевая кобылка", "Малая крестовичка", "Конёк белополосый (белополосая кобылка)", "Конек обыкновенный", "Конек обыкновенный", "Кобылка темнокрылая", "Краснокрылая кобылка", "Краснокрылая кобылка", "Степная кобылка", "Гребневка": + locust.locust_type_id = "4"; + break; + case "Азиатская перелётная саранча": + locust.locust_type_id = "3"; + break; + case "Итальянский прус": + locust.locust_type_id = "1"; + break; + case "Мароккская саранча, мароккская кобылка, марокканка": + locust.locust_type_id = "2"; + break; + default: + throw new CustomException(200, 10000, "Not find swarms_height: (" + locust.locust+")", null, true); } - hConn.disconnect(); - } catch (IOException e) { - e.printStackTrace(); + }else{ + throw new CustomException(200, 10000, "Field nameSubject is null", null, true); } - String base64 = sb.toString(); - if (base64.length() > 10) { - //Так как мне присылаю неправильный jSOM то пытаюсь его поправить,. - base64 = base64.replace("[", "[\""); - base64 = base64.replace("]", "\"]"); - base64 = base64.replace(", ", "\",\""); + //фаза саранчи + if (!jsonObjSub.isNull("phaseEvolutionName")) + locust.phase = jsonObjSub.getString("phaseEvolutionName"); - String strFile = "O:\\temp\\CCALM\\ru_" + locust.eid; - int pos = 0; + locust.locust_have = "3"; + if (locust.phase != null) { + if (locust.phase.equals("Кубышка")) locust.locust_have = "2"; //Кубышка = Яйца + if (locust.phase.equals("Гусеница")) locust.locust_have = "3"; + if (locust.phase.equals("Личинка 2-го возраста")) locust.locust_have = "3"; + if (locust.phase.equals("Личинка 3-го возраста")) locust.locust_have = "3"; + if (locust.phase.equals("Личинка 4-го возраста")) locust.locust_have = "3"; + if (locust.phase.equals("Личинка 5-го возраста")) locust.locust_have = "3"; + if (locust.phase.equals("Имаго")) locust.locust_have = "5"; + } - JSONArray jsonArrayIMGS = new JSONArray(base64); - for (Object oStr : jsonArrayIMGS) { - String jsonObjIMG = (String) oStr; - pos++; - if (pos > 3) break; - //try { - // BufferedWriter writer = new BufferedWriter(new FileWriter(strFile)); - // writer.write(jsonObjIMG); - // writer.close(); - //} catch (IOException e1) { - // e1.printStackTrace(); - //} - byte[] decodedString = null; + //Если эта анкета "Имаго" то записываем плотность имаго на m2 + if (locust.locust_have.equals("5")) { + if (!jsonObjSub.isNull("subPestCount")) + locust.imago_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); + } + //Если эта анкета "Кубышка"="Яйца" то записываем плотность кулиг на m2 + if (locust.locust_have.equals("2")) { + if (!jsonObjSub.isNull("subPestCount")) + locust.eggs_capsules_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); + } + //Если эта анкета "Кулиги" то записываем плотность кулиг на m2 + if (locust.locust_have.equals("4")) { + if (!jsonObjSub.isNull("subPestCount")) + locust.kuliguli_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); + } + //Если эта анкета "Личинок" то записываем плотность личинок на m2 + if (locust.locust_have.equals("3")) { + if (!jsonObjSub.isNull("subPestCount")) + locust.larva_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); + } + + //Биотоп + switch (jsonObjSub.getString("faoBiotopeName")) { + case "CIT степь": + locust.bio_biotope_id = "1"; + break; + case "CIT залежь": + locust.bio_biotope_id = "2"; + break; + case "CIT посевы": + locust.bio_biotope_id = "3"; + break; + case "CIT пастбища": + locust.bio_biotope_id = "11"; + break; + case "CIT холмы, горы": + locust.bio_biotope_id = "19"; + break; + case "DMA равнины": + locust.bio_biotope_id = "4"; + break; + case "DMA посевы": + locust.bio_biotope_id = "6"; + break; + case "DMA пастбища": + locust.bio_biotope_id = "13"; + break; + case "DMA холмы, горы": + locust.bio_biotope_id = "14"; + break; + case "LMI низкие сухие тростники": + locust.bio_biotope_id = "7"; + break; + case "LMI высокие влажные тростники": + locust.bio_biotope_id = "8"; + break; + case "LMI другое": + locust.bio_biotope_id = "10"; + break; + case "Другие саранчовые на посевах": + locust.bio_biotope_id = "15"; + break; + case "Другие саранчовые на равнине": + locust.bio_biotope_id = "16"; + break; + case "Другие саранчовые на холмах": + locust.bio_biotope_id = "17"; + break; + case "Другое": + locust.bio_biotope_id = "18"; + break; + default: + locust.bio_biotope_id = null; + break; + } + + //Если те виды что нам нужны + if (regionName == null || regionName.isEmpty() || locust.lat_center == null || Double.parseDouble(locust.lat_center) == 0 || locust.lon_center == null || Double.parseDouble(locust.lon_center) == 0 || locust.locust.equals("Совка ипсилон") || locust.locust.equals("Восточный майский хрущ") || locust.locust.equals("Кукурузный стеблевой мотылек") || locust.locust.equals("Картофельная, или болотная совка, лиловатая яровая совка") || locust.locust.equals("Луговой мотылёк") || locust.locust.equals("Хлопковая совка") || locust.locust.equals("Стеблевой кукурузный мотылек") || locust.locust.equals("Восточная луговая совка") || locust.locust.equals("Коричневая щитовка") || locust.locust.equals("Продолговатая (чайная) подушечница") || locust.locust.equals("Яблоневая запятовидная щитовка") || locust.locust.equals("Виноградная филлоксера") || locust.locust.equals("Бахчевая коровка")) { + + } else { + + if (locust.locust_type_id.isEmpty()) { + System.out.println("locust.locust = "+locust.locust); + model.addAttribute("PreviewTable", "locust.locust_type_id == 0 locust name = " + locust.locust); + throw new CustomException(200, 10000, "Error, not find locust.locust = "+locust.locust,null,true); + } + if (locust.region_id.isEmpty()) { + System.out.println("locust.region = "+regionName); + model.addAttribute("PreviewTable", "locust.region_id == 0 region name = " + regionName); + throw new CustomException(200, 10000, "Error, not find locust.region = "+regionName,null,true); + } + + //Тех полей что нет в анкете вствляю в комментарии + try { + locust.description = ""; + + if (jsonObjSub.getBoolean("notFound")) + locust.description += "Вредитель не обнаружен: " + jsonObjSub.getString("nameSubject") + "\n"; + else + locust.description += "Вредитель обнаружен: " + jsonObjSub.getString("nameSubject") + "\n"; + + if (!jsonObjSub.isNull("phaseEvolutionName")) + locust.description += "Фаза: " + jsonObjSub.getString("phaseEvolutionName") + "\n"; //Так как фаза у росиян более подробная + if (!jsonObjSub.isNull("subPestCount")) { + locust.description += "Вредителей: " + jsonObjSub.getFloat("subPestCount"); + if (!jsonObjSub.isNull("unitName")) + locust.description += " " + jsonObjSub.getString("unitName"); + locust.description += "\n"; + } + + if (!jsonObj.isNull("cropCurrentType")) + locust.description += "Тип сева: " + jsonObj.getString("cropCurrentType") + "\n"; + if (!jsonObj.isNull("cropCurrentCulture")) + locust.description += "Наименование культуры: " + jsonObj.getString("cropCurrentCulture") + "\n"; + if (!jsonObj.isNull("cropCurrentCultureSort")) + locust.description += "Наименование сорта культуры: " + jsonObj.getString("cropCurrentCultureSort") + "\n"; + if (!jsonObj.isNull("cropCurrentGrowthPhase")) + locust.description += "Фаза роста культуры: " + jsonObj.getString("cropCurrentGrowthPhase") + "\n"; + if (!jsonObj.isNull("cropFieldArea")) { + locust.description += "Площадь поля: " + jsonObj.getFloat("cropFieldArea") + "\n"; + locust.bio_hectare = String.valueOf(jsonObj.getFloat("cropFieldArea")); + } + + + } catch (Exception ex) { + ex.printStackTrace(); + } + + locust.terrain = "null"; //У росиян нет сельского округа + + row = ""; + if (locust.region_id == null || locust.region_id.isEmpty() || locust.district_id == null || locust.district_id.isEmpty() || locust.locust_type_id == null || locust.locust_type_id.isEmpty()) { + row = ""; + } + row += ""; + row += "\n"; + + //Если записи не существует то вставляем если существует то обновляем + boolean exists = false; //Is there a record. + Statement st; + try { + st = conn.createStatement(); + //ResultSet rs=null; try { - decodedString = Base64.getDecoder().decode(jsonObjIMG); - } catch (Exception e) { - e.printStackTrace(); - model.addAttribute("PreviewTable", "Error decode"); + sql = "select 1 from main.frmlocust where eid=" + String.valueOf(locust.eid); + rs = st.executeQuery(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error select"); return "json"; } + if (rs != null) { + if (rs.next()) + exists = true; + } + st.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error select 2"); + return "json"; + } - if (decodedString != null) { + PreparedStatement stmt = null; + sql = ""; + if (exists) { + System.out.println(String.valueOf(cntV)+") update main.frmlocust"); + sql = "update main.frmlocust set\n" + + " eid=?,\n" + + " lat_center=?,\n" + + " lon_center=?,\n" + + " country_id=?,\n" + + " region_id=?,\n" + + " area=?,\n" + + " district=?,\n" + + " date=TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" + + " description=?,\n" + + " geom=ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" + + " locust_type_id=?,\n" + + " imago_density=?,\n" + + " kuliguli_density=?,\n" + + " larva_density=?,\n" + + " bio_hectare=?\n," + + " eggs_capsules_density=?,\n" + + " bio_biotope_id=?\n" + + " where eid='" + locust.eid + "'"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error prepare 1"); + return "json"; + } + } else { + System.out.println(String.valueOf(cntV)+") insert into main.frmlocust"); + sql = "insert into main.frmlocust(\n" + + " eid,\n" //1 + + " lat_center,\n" //2 + + " lon_center,\n" //3 + + " country_id,\n" //4 + + " region_id,\n" //5 + + " area,\n" //6 + + " district,\n" //7 + + " date,\n" //8 + + " description,\n" //9 + + " geom,\n" //10 + + " locust_type_id,\n" //11 + + " imago_density,\n" //12 + + " kuliguli_density,\n" //13 + + " larva_density,\n" //14 + + " bio_hectare,\n" //15 + + " eggs_capsules_density,\n" //16 + + " bio_biotope_id\n" //17 + + ")values(\n" + + " ?,\n" //1 eid + + " ?,\n" //2 lat1 + + " ?,\n" //3 lon1 + + " ?,\n" //4 country_id + + " ?,\n" //5 region_id + + " ?,\n" //6 district (area) + + " ?,\n" //7 district (area) + + " TO_TIMESTAMP(?, 'DD.MM.YYYY HH24:MI'),\n" //8 date + + " ?,\n" //9 description + + " ST_SetSRID(ST_GeomFromGeoJSON(?),4326),\n" //10 geom + + " ?,\n" //11 locust_type_id + + " ?,\n" //12 imago_density + + " ?,\n" //13 kuliguli_density + + " ?,\n" //14 larva_density + + " ?,\n" //15 + + " ?,\n" //16 + + " ?\n" //17 + + ")"; + try { + stmt = conn.prepareStatement(sql); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error prepare 2"); + return "json"; + } + } + + try { + stmt.setLong(1, Long.parseLong(locust.eid)); + stmt.setDouble(2, Double.parseDouble(locust.lat_center)); + stmt.setDouble(3, Double.parseDouble(locust.lon_center)); + stmt.setInt(4, 7); + stmt.setInt(5, Integer.parseInt(locust.region_id)); + stmt.setString(6, locust.district); //Пишу в поле "area" + stmt.setString(7, null); + stmt.setString(8, locust.date); //27.04.2020 09:17 + stmt.setString(9, locust.description); + stmt.setString(10, locust.drawPolygon); + stmt.setInt(11, Integer.parseInt(locust.locust_type_id)); + if (locust.imago_density != null) + stmt.setFloat(12, Float.parseFloat(locust.imago_density)); + else + stmt.setNull(12, Types.FLOAT); + if (locust.kuliguli_density != null) + stmt.setFloat(13, Float.parseFloat(locust.kuliguli_density)); + else + stmt.setNull(13, Types.FLOAT); + if (locust.larva_density != null) + stmt.setFloat(14, Float.parseFloat(locust.larva_density)); + else + stmt.setNull(14, Types.FLOAT); + if (locust.bio_hectare != null) + stmt.setFloat(15, Float.parseFloat(locust.bio_hectare)); + else + stmt.setNull(15, Types.FLOAT); + if (locust.eggs_capsules_density != null) + stmt.setFloat(16, Float.parseFloat(locust.eggs_capsules_density)); + else + stmt.setNull(16, Types.FLOAT); + if (locust.bio_biotope_id != null) + stmt.setFloat(17, Float.parseFloat(locust.bio_biotope_id)); + else + stmt.setNull(17, Types.INTEGER); + + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error set data"); + return "json"; + } + //Выпоняю запрос на свтавку либо обновление + try { + stmt.execute(); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error execute 0"); + return "json"; + } + cntV++; + + //Скачиваю фотографию для анкеты + sb = new StringBuilder(); + try { + String strURL = "https://rscagex.ru/pmon/rest/getPhotosByParentId?token=QVOUE97HBSI6LBSGJGQZMP3KPSS1QK&parentId=" + locust.eid; + URL url = new URL(strURL); + HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); + hConn.setRequestMethod("GET"); + //hConn.setRequestProperty("Range","bytes=" + posStart + "-" + posEnd); + hConn.connect(); + int responseCode = hConn.getResponseCode(); + if (responseCode / 100 == 2) //Code 206 is "Partial Content" + { + InputStream inputStream = hConn.getInputStream(); + //FileOutputStream outputStream = new FileOutputStream(strFile); + int bytesRead; + byte[] buffer = new byte[BUFFER_SIZE]; + while ((bytesRead = inputStream.read(buffer)) != -1) { + //outputStream.write(buffer, 0, bytesRead); + sb.append(new String(buffer, 0, bytesRead)); + } + //outputStream.close(); + inputStream.close(); + } + hConn.disconnect(); + } catch (IOException e) { + e.printStackTrace(); + } + + String base64 = sb.toString(); + if (base64.length() > 10) { + //Так как мне присылаю неправильный jSOM то пытаюсь его поправить,. + base64 = base64.replace("[", "[\""); + base64 = base64.replace("]", "\"]"); + base64 = base64.replace(", ", "\",\""); + + String strFile = "O:\\temp\\CCALM\\ru_" + locust.eid; + int pos = 0; + + JSONArray jsonArrayIMGS = new JSONArray(base64); + for (Object oStr : jsonArrayIMGS) { + String jsonObjIMG = (String) oStr; + pos++; + if (pos > 3) break; + + //try { + // BufferedWriter writer = new BufferedWriter(new FileWriter(strFile)); + // writer.write(jsonObjIMG); + // writer.close(); + //} catch (IOException e1) { + // e1.printStackTrace(); + //} + + byte[] decodedString = null; try { - FileUtils.writeByteArrayToFile(new File(strFile + "_" + pos + ".jpg"), decodedString); + decodedString = Base64.getDecoder().decode(jsonObjIMG); + } catch (Exception e) { + e.printStackTrace(); + model.addAttribute("PreviewTable", "Error decode"); + return "json"; + } + + if (decodedString != null) { + try { + FileUtils.writeByteArrayToFile(new File(strFile + "_" + pos + ".jpg"), decodedString); + } catch (IOException e) { + e.printStackTrace(); + } + } + decodedString = null; + + BufferedImage imageOnDisk = null; + try { + imageOnDisk = ImageIO.read(new File(strFile + "_" + pos + ".jpg")); } catch (IOException e) { e.printStackTrace(); } - } - decodedString = null; - - BufferedImage imageOnDisk = null; - try { - imageOnDisk = ImageIO.read(new File(strFile + "_" + pos + ".jpg")); - } catch (IOException e) { - e.printStackTrace(); - } - if (imageOnDisk != null) { - Image img; - BufferedImage buffered; - if (imageOnDisk.getWidth() > imageOnDisk.getHeight()) { - img = imageOnDisk.getScaledInstance(1024, 768, Image.SCALE_DEFAULT); - buffered = new BufferedImage(1024, 768, BufferedImage.TYPE_INT_RGB); - buffered.getGraphics().drawImage(img, 0, 0, null); - } else { - img = imageOnDisk.getScaledInstance(768, 1024, Image.SCALE_DEFAULT); - buffered = new BufferedImage(768, 1024, BufferedImage.TYPE_INT_RGB); - buffered.getGraphics().drawImage(img, 0, 0, null); - } - try { - //BufferedImage bIMG = toBufferedImage(img); - ImageIO.write(buffered, "jpg", new File(strFile + "_" + pos + ".jpg")); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - - if (pos > 3) { - break; - } else { - sql = ""; - if (pos == 1) { - sql = "update main.frmlocust set image_name1='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; - } - if (pos == 2) { - sql = "update main.frmlocust set image_name2='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; - } - if (pos == 3) { - sql = "update main.frmlocust set image_name3='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; - } - if (sql.length() > 0) { + if (imageOnDisk != null) { + Image img; + BufferedImage buffered; + if (imageOnDisk.getWidth() > imageOnDisk.getHeight()) { + img = imageOnDisk.getScaledInstance(1024, 768, Image.SCALE_DEFAULT); + buffered = new BufferedImage(1024, 768, BufferedImage.TYPE_INT_RGB); + buffered.getGraphics().drawImage(img, 0, 0, null); + } else { + img = imageOnDisk.getScaledInstance(768, 1024, Image.SCALE_DEFAULT); + buffered = new BufferedImage(768, 1024, BufferedImage.TYPE_INT_RGB); + buffered.getGraphics().drawImage(img, 0, 0, null); + } try { - st = conn.createStatement(); - st.execute(sql); - st.close(); - } catch (SQLException ex) { + //BufferedImage bIMG = toBufferedImage(img); + ImageIO.write(buffered, "jpg", new File(strFile + "_" + pos + ".jpg")); + } catch (IOException ex) { ex.printStackTrace(); - model.addAttribute("PreviewTable", "Error update img"); - return "json"; + } + } + + + if (pos > 3) { + break; + } else { + sql = ""; + if (pos == 1) { + sql = "update main.frmlocust set image_name1='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; + } + if (pos == 2) { + sql = "update main.frmlocust set image_name2='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; + } + if (pos == 3) { + sql = "update main.frmlocust set image_name3='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; + } + if (sql.length() > 0) { + try { + st = conn.createStatement(); + st.execute(sql); + st.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + model.addAttribute("PreviewTable", "Error update img"); + return "json"; + } } } } } } - } - } //equals("Вредители") + } //equals("Вредители") + + } } + table += row; } - - table += row; - } - System.out.println("Обработка = "+String.valueOf(cntO)); - System.out.println("Вредители = "+String.valueOf(cntV)); + System.out.println("Обработка = "+String.valueOf(cntO)); + System.out.println("Вредители = "+String.valueOf(cntV)); - table += "
Ext idLatitude (Широта)Longitude (Долгота)Oblast (область)District (Район)Сельский округХозяйство или местностьВид саранчиФазаЭПВЗаселено ГаДата
" + String.valueOf(cntO+cntV) + "" + locust.eid + "" + locust.lat_center + "" + locust.lon_center + "" + regionName + " = " + locust.region_id + "" + locust.district + " = " + locust.district_id + "" + locust.terrain + "" + locust.village + "" + locust.locust + " = " + locust.locust_type_id + "" + locust.phase + " = " + locust.locust_have + "" + locust.evp + "" + locust.size + " = " + locust.drawPolygon + "" + locust.date + "
" + String.valueOf(cntO+cntV) + "" + locust.eid + "" + locust.lat_center + "" + locust.lon_center + "" + regionName + " = " + locust.region_id + "" + locust.district + " = " + locust.district_id + "" + locust.terrain + "" + locust.village + "" + locust.locust + " = " + locust.locust_type_id + "" + locust.phase + " = " + locust.locust_have + "" + locust.evp + "" + locust.size + " = " + locust.drawPolygon + "" + locust.date + "
"; + table += ""; - //json=json.substring(0,json.length()-1); //Удаляю последнюю запятую - //json+="\n]}"; + //json=json.substring(0,json.length()-1); //Удаляю последнюю запятую + //json+="\n]}"; - //Сохраняю lastDate в базу данных - try { - Statement st = conn.createStatement(); - st.execute("insert into integration.days_ru(date,count)values('" + lastDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "'," + String.valueOf(cntV+cntO) + ");"); - st.close(); - } catch (SQLException ex) { - ex.printStackTrace(); - model.addAttribute("PreviewTable", "Error update img"); - return "json"; + //Сохраняю lastDate в базу данных + try { + Statement st = conn.createStatement(); + st.execute("insert into integration.days_ru(date,count)values('" + lastDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "'," + String.valueOf(cntV+cntO) + ");"); + st.close(); + } catch (SQLException ex) { + model.addAttribute("PreviewTable", "Error update img"); + throw new CustomException(200, 10000, ex.getMessage(),null,true); + } } } - } - model.addAttribute("PreviewTable",table); - //model.addAttribute("PreviewGEOJSON",json); - model.addAttribute("PreviewSQL",sqlData); + model.addAttribute("PreviewTable",table); + //model.addAttribute("PreviewGEOJSON",json); + model.addAttribute("PreviewSQL",sqlData); + } catch (CustomException e) { + if(e.isSaveToLog()) { + String uuid = UUID.randomUUID().toString(); + logger.error(MarkerFactory.getMarker(uuid), e.getMessage(), e); + } + } catch (Exception ex) { + String uuid = UUID.randomUUID().toString(); + logger.error(MarkerFactory.getMarker(uuid), ex.getMessage(), ex); + } return "json"; } //--------------------------------------------------------------------------- @@ -1837,7 +1886,7 @@ public class AcceptJSON implements ServletContextAware { result.larva_born = null; // not used if(!obj.isNull("hoppers_hatching") && !obj.optString("hoppers_hatching","").isBlank()){ - switch (obj.optString("hoppers_hatching",null).replace("'", "").trim().trim()) { + switch (obj.optString("hoppers_hatching",null).replace("'", "").trim()) { case "Beginning", "Начало": result.larva_born_id="1"; result.larva_born_uid="392db9f2-bfaa-44e0-8ca3-bb3cf1ff937a"; diff --git a/src/main/java/org/ccalm/main/models/FrmLocustModel.java b/src/main/java/org/ccalm/main/models/FrmLocustModel.java index 2e6c34d..e8a6bdc 100644 --- a/src/main/java/org/ccalm/main/models/FrmLocustModel.java +++ b/src/main/java/org/ccalm/main/models/FrmLocustModel.java @@ -2,7 +2,7 @@ package org.ccalm.main.models; import lombok.Getter; import lombok.Setter; -import org.ccalm.main.utils.CustomException; +//import org.ccalm.main.utils.CustomException; import java.sql.Types; diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html index 68f158e..16b62bd 100644 --- a/src/main/resources/templates/index.html +++ b/src/main/resources/templates/index.html @@ -306,10 +306,10 @@