AcceptJSON_RUS model

This commit is contained in:
2025-07-23 07:37:24 +05:00
parent e3f93fed10
commit fab0c34ffb
2 changed files with 302 additions and 598 deletions

View File

@ -5,7 +5,6 @@ package org.ccalm.main;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.Image; import java.awt.Image;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*; import java.io.*;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URI; import java.net.URI;
@ -430,36 +429,10 @@ public class AcceptJSON implements ServletContextAware {
* @param skip * @param skip
* @return * @return
*/ */
@RequestMapping(value = {"/AcceptJSON_RUS", "/api/locust/v01/AcceptJSON_RUS"}, method = { RequestMethod.GET, RequestMethod.POST }) @RequestMapping(value = {"/AcceptJSON_RUS", "/api/locust/v01/AcceptJSON_RUS"}, method = { RequestMethod.GET, RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE)
public String acceptCSV(@ModelAttribute User user, Model model,@RequestParam(required=false,name="file") MultipartFile file,@RequestParam(required=false,name="skip",defaultValue = "0") Boolean skip) { public String acceptCSV(@ModelAttribute User user, Model model,@RequestParam(required=false,name="file") MultipartFile file,@RequestParam(required=false,name="skip",defaultValue = "0") Boolean skip) {
JSONObject json = new JSONObject();
try{ try{
Connection conn = null;
try {
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);
}
//Set UTC time
Statement stm=null;
try {
stm = conn.createStatement();
try {
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="<table border=\"1\">";
table+="<tr style=\"background-color: #e0e0e0;\"><th>№</th><th>Ext id</th><th>Latitude (Широта)</th><th>Longitude (Долгота)</th><th>Oblast (область)</th><th>District (Район)</th><th>Сельский округ</th><th>Хозяйство или местность</th><th>Вид саранчи</th><th>Фаза</th><th>ЭПВ</th><th>Заселено Га</th><th>Дата</th></tr>";
//I select the maximum date, check that it is less than the current minus 2 days and try to load it //I select the maximum date, check that it is less than the current minus 2 days and try to load it
LocalDate lastDate = null; LocalDate lastDate = null;
String sql= """ String sql= """
@ -478,36 +451,8 @@ public class AcceptJSON implements ServletContextAware {
if(lastDate==null) if(lastDate==null)
lastDate = LocalDate.parse("2025-04-01"); lastDate = LocalDate.parse("2025-04-01");
Statement stt = null; //Statement stt = null;
ResultSet rs = 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 //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))){ while(lastDate.isBefore(LocalDate.now().minusDays(3))){
@ -548,16 +493,12 @@ public class AcceptJSON implements ServletContextAware {
String content=sb.toString(); String content=sb.toString();
if(content!=null && !content.isEmpty()) { if(content!=null && !content.isEmpty()) {
//byte[] data = sb.toByteArray(in); int count = 0;
//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); JSONArray jsonArray = new JSONArray(content);
for (Object o : jsonArray) { for (Object o : jsonArray) {
JSONObject jsonObj = (JSONObject) o; JSONObject jsonObj = (JSONObject) o;
FrmLocustModel locust = new FrmLocustModel(); FrmLocustModel locust = new FrmLocustModel();
locust.company_uid = "2925b0a4-2bc5-4083-b3f1-9fddd909289e"; //ФГБУ "Россельхозцентр"
try{ try{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
@ -567,11 +508,6 @@ public class AcceptJSON implements ServletContextAware {
throw new CustomException(200, 10000, "Date error: " + jsonObj.optString("date","null"), null, true); throw new CustomException(200, 10000, "Date error: " + jsonObj.optString("date","null"), null, true);
} }
String regionName="";
if (!jsonObj.isNull("regionName"))
regionName = jsonObj.getString("regionName");
if (!jsonObj.isNull("townName")) if (!jsonObj.isNull("townName"))
locust.district = jsonObj.getString("townName"); locust.district = jsonObj.getString("townName");
@ -591,164 +527,134 @@ public class AcceptJSON implements ServletContextAware {
if (!jsonObj.isNull("polygonArea")) if (!jsonObj.isNull("polygonArea"))
locust.size = String.valueOf(jsonObj.getDouble("polygonArea")); locust.size = String.valueOf(jsonObj.getDouble("polygonArea"));
//jsonObj.drawPolygon Краснодар if (!jsonObj.isNull("regionName") || jsonObj.getString("regionName").isEmpty()){
if (!regionName.isEmpty()) { sql= "select id from main.countriesregions where name ilike :regionName";
//Выбираю ID области parameters = new MapSqlParameterSource();
locust.region_id = ""; parameters.addValue("regionName", "%" + jsonObj.getString("regionName") + "%");
//Statement stt = null; ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
//ResultSet rs = null; for (String s : ret) {
try { JSONObject rObj = new JSONObject(s);
if(!rObj.isNull("id")) {
stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); locust.region_id = String.valueOf(rObj.getLong("id"));
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) {
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);
} }
} }
if(!locust.region_id.isEmpty() && !jsonObj.isNull("townName")) {
/*if(locust.region_id.isEmpty()){ locust.district = jsonObj.getString("townName");
if(regionName.indexOf("Воронежс<D0B6><D181>ая область")>=0) locust.region_id="110"; switch(locust.district)
if(regionName.indexOf("Кра<D180><D0B0>нодарский край")>=0) locust.region_id="164"; {
if(regionName.indexOf("Астраха<D185><D0B0>ская область")>=0) locust.region_id="68"; //dayOfYear: 97 at year: 2022 = 07.04.2022 case "Алапаевский район": locust.district = "городской округ Алапаевское";
if(regionName.indexOf("Астраханская област<D181><D182>")>=0) locust.region_id="68"; // dayOfYear: 101 at year: 2022 = 11.04.2022 break;
}*/ case "Сухоложский район": locust.district = "городской округ Сухой Лог";
break;
if (locust.region_id.length() > 0) { case "Талицкий район": locust.district = "Талицкий городской округ";
//Выбираю id региона (main.countriesdistricts) break;
locust.district_id = ""; case "Артинский район": locust.district = "Талицкий городской округ";
stt = null; break;
rs = null; case "Богдановичский район": locust.district = "городской округ Богданович";
try { break;
case "Красноуфимский район": locust.district = "Красноуфимский округ";
if (locust.district.equals("Алапаевский район")) break;
locust.district = "городской округ Алапаевское"; case "Белоярский район": locust.region_id = "210";
if (locust.district.equals("Сухоложский район")) break;
locust.district = "городской округ Сухой Лог"; case "Пышминский район": locust.district = "Пышминский городской округ";
if (locust.district.equals("Талицкий район")) break;
locust.district = "Талицкий городской округ"; case "Ирбитский район": locust.district = "городской округ Ирбитское";
if (locust.district.equals("Артинский район")) break;
locust.district = "Талицкий городской округ"; case "Фрязино г.о.": locust.district = "городской округ Фрязино";
if (locust.district.equals("Богдановичский район")) break;
locust.district = "городской округ Богданович"; case "Коломенский г.о.": locust.district = "Коломенский район";
if (locust.district.equals("Красноуфимский район")) break;
locust.district = "Красноуфимский округ"; case "Протвино г.о.": locust.district = "городской округ Протвино";
if (locust.district.equals("Белоярский район")) locust.region_id = "210"; break;
if (locust.district.equals("Пышминский район")) case "Зарайск г.о.": locust.district = "Зарайский район";
locust.district = "Пышминский городской округ"; break;
if (locust.district.equals("Ирбитский район")) case "Анапский район": locust.district = "городской округ Анапа";
locust.district = "городской округ Ирбитское"; break;
if (locust.district.equals("Фрязино г.о.")) locust.district = "городской округ Фрязино"; case "Луховицы г.о.": locust.district = "Луховицкий район";
if (locust.district.equals("Коломенский г.о.")) locust.district = "Коломенский район"; break;
if (locust.district.equals("Протвино г.о.")) case "Дергачевский район": locust.district = "Дергачёвский район";
locust.district = "городской округ Протвино"; break;
if (locust.district.equals("Зарайск г.о.")) locust.district = "Зарайский район"; case "Чистоозерный район": locust.district = "Чистоозёрный район";
if (locust.district.equals("Анапский район")) locust.district = "городской округ Анапа"; break;
if (locust.district.equals("Луховицы г.о.")) locust.district = "Луховицкий район"; case "Сунжа город": locust.district = "Сунженский район";
if (locust.district.equals("Дергачевский район")) break;
locust.district = "Дергачёвский район"; case "Буденновский район": locust.district = "Будённовский район";
if (locust.district.equals("Чистоозерный район")) break;
locust.district = "Чистоозёрный район"; case "Новоселовский район": {
if (locust.district.equals("Сунжа город")) locust.district = "Сунженский район";
if (locust.district.equals("Буденновский район"))
locust.district = "Будённовский район";
if (locust.district.equals("Новоселовский район")) {
locust.district = "Новоселицкий район"; locust.district = "Новоселицкий район";
locust.region_id = "168"; locust.region_id = "168";
} }break;
if (locust.district.equals("Тимашевский район")) locust.district = "Тимашёвский район"; case "Тимашевский район": locust.district = "Тимашёвский район";
if (locust.district.equals("Славгородский район")) break;
locust.district = "городской округ Славгород"; case "Славгородский район": locust.district = "городской округ Славгород";
if (locust.district.equals("Режевский район")) break;
locust.district = "Режевской городской округ"; case "Режевский район": locust.district = "Режевской городской округ";
if (locust.district.equals("Веселовский район")) locust.district = "Весёловский район"; break;
if (locust.district.equals("Карабулак город")) case "Веселовский район": locust.district = "Весёловский район";
locust.district = "городской округ Карабулак"; break;
if (locust.district.equals("Пугачевский район")) locust.district = "Пугачёвский район"; case "Карабулак город": locust.district = "городской округ Карабулак";
if (locust.district.equals("Кущевский район")) locust.district = "Кущёвский район"; break;
if (locust.district.equals("Репьевский район")) locust.district = "Репьёвский район"; case "Пугачевский район": locust.district = "Пугачёвский район";
if (locust.district.equals("Калачевский район")) locust.district = "Калачёвский район"; break;
if (locust.district.equals("Гайский район")) case "Кущевский район": locust.district = "Кущёвский район";
locust.district = "Гайский городской округ"; break;
if (locust.district.equals("Новохоперский район")) case "Репьевский район": locust.district = "Репьёвский район";
locust.district = "Новохопёрский район"; break;
if (locust.district.equals("Федоровский район")) locust.district = "Фёдоровский район"; case "Калачевский район": locust.district = "Калачёвский район";
if (locust.district.equals("Серебряные Пруды г.о.")) break;
locust.district = "городской округ Серебряные Пруды"; case "Гайский район": locust.district = "Гайский городской округ";
if (locust.district.equals("Минераловодский район")) break;
locust.district = "Минераловодский городской округ"; case "Новохоперский район": locust.district = "Новохопёрский район";
if (locust.district.equals("Рузский г.о.")) locust.district = "Рузский район"; break;
if (locust.district.equals("Воробьевский район")) case "Федоровский район": locust.district = "Фёдоровский район";
locust.district = "Воробьёвский район"; break;
if (locust.district.equals("Ачитский район")) case "Серебряные Пруды г.о.": locust.district = "городской округ Серебряные Пруды";
locust.district = "Ачитский городской округ"; break;
if (locust.district.equals("Грачевский район")) locust.district = "Грачёвский район"; case "Минераловодский район": locust.district = "Минераловодский городской округ";
if (locust.district.equals("Уссурийский район")) break;
locust.district = "Уссурийский городской округ"; case "Рузский г.о.": locust.district = "Рузский район";
if (locust.district.equals("Сорочинский район")) break;
locust.district = "Сорочинский городской округ"; case "Воробьевский район": locust.district = "Воробьёвский район";
if (locust.district.equals("Ясненский район")) break;
locust.district = "Ясненский городской округ"; case "Ачитский район": locust.district = "Ачитский городской округ";
if (locust.district.equals("Белогорский муниципальный округ")) { break;
case "Грачевский район": locust.district = "Грачёвский район";
break;
case "Уссурийский район": locust.district = "Уссурийский городской округ";
break;
case "Сорочинский район": locust.district = "Сорочинский городской округ";
break;
case "Ясненский район": locust.district = "Ясненский городской округ";
break;
case "Белогорский муниципальный округ": {
locust.district = "городской округ Белгород"; locust.district = "городской округ Белгород";
locust.region_id = "69"; locust.region_id = "69";
}break;
} }
stt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); sql = "select id from main.countriesdistricts where region_id=" + locust.region_id + " and name like '%" + locust.district + "%';";
String sql_query = "select id from main.countriesdistricts where region_id=" + locust.region_id + " and name like '%" + locust.district + "%';"; parameters = new MapSqlParameterSource();
rs = stt.executeQuery(sql_query); ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
if (rs != null) { for (String s : ret) {
try { JSONObject rObj = new JSONObject(s);
if (rs.next()) { if (!rObj.isNull("id")) {
locust.district_id = rs.getString(1); locust.district_id = String.valueOf(rObj.getLong("id"));
}
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);
} }
} }
//if(locust.district_id==null){
// throw new CustomException(200, 10000, "Not find district: "+locust.district,null,true);
//}
}else{
throw new CustomException(200, 10000, "Not find region: "+jsonObj.getString("regionName"),null,true);
} }
}else{ }else{
throw new CustomException(200, 10000, "regionName.isEmpty()",null,true); throw new CustomException(200, 10000, "regionName.isEmpty()",null,true);
} }
String row = "";
if (!jsonObj.isNull("subjectList")) { if (!jsonObj.isNull("subjectList")) {
JSONArray jsonArraySub = jsonObj.getJSONArray("subjectList"); JSONArray jsonArraySub = jsonObj.getJSONArray("subjectList");
@ -757,9 +663,10 @@ public class AcceptJSON implements ServletContextAware {
JSONObject jsonObjSub = (JSONObject) o2; JSONObject jsonObjSub = (JSONObject) o2;
locust.eid = String.valueOf(jsonObjSub.getInt("id")); locust.eid = String.valueOf(jsonObjSub.getInt("id"));
locust.phytoType = jsonObjSub.getString("phytoType"); //"Вредители" или "Обработка" locust.phytoType = jsonObjSub.getString("phytoType"); //"Вредители" или "Обработка"
if (locust.phytoType.equals("Обработка")) { if (locust.phytoType.equals("Обработка")) {
locust.insecticide_name = jsonObjSub.getString("nameSubject"); //Наименование действующего вещества /*locust.insecticide_name = jsonObjSub.getString("nameSubject"); //Наименование действующего вещества
if (!jsonObjSub.isNull("nameLatSubject")) if (!jsonObjSub.isNull("nameLatSubject"))
locust.insecticide_active_substance = jsonObjSub.getString("nameLatSubject"); //Латинское наименование действующего вещества locust.insecticide_active_substance = jsonObjSub.getString("nameLatSubject"); //Латинское наименование действующего вещества
if (!jsonObjSub.isNull("protectionDoze")) if (!jsonObjSub.isNull("protectionDoze"))
@ -927,12 +834,11 @@ public class AcceptJSON implements ServletContextAware {
throw new CustomException(200, 10000, ex.getMessage(),null,true); throw new CustomException(200, 10000, ex.getMessage(),null,true);
} }
cntO++; cntO++;*/
} else if (locust.phytoType.equals("Вредители")) { } else if (locust.phytoType.equals("Вредители")) {
//Вид саранчи
locust.locust_type_id = "";
//Вид саранчи
if(!jsonObjSub.isNull("nameSubject") && !jsonObjSub.optString("nameSubject","").isBlank()) { if(!jsonObjSub.isNull("nameSubject") && !jsonObjSub.optString("nameSubject","").isBlank()) {
locust.locust = jsonObjSub.getString("nameSubject"); locust.locust = jsonObjSub.getString("nameSubject");
switch (jsonObjSub.optString("nameSubject",null).replace("'", "").trim()) { switch (jsonObjSub.optString("nameSubject",null).replace("'", "").trim()) {
@ -949,51 +855,58 @@ public class AcceptJSON implements ServletContextAware {
locust.locust_type_id = "2"; locust.locust_type_id = "2";
break; break;
default: default:
throw new CustomException(200, 10000, "Not find swarms_height: (" + locust.locust+")", null, true); throw new CustomException(200, 10000, "Not find nameSubject: (" + locust.locust+")", null, true);
} }
}else{ }else{
throw new CustomException(200, 10000, "Field nameSubject is null", null, true); throw new CustomException(200, 10000, "Field nameSubject is null", null, true);
} }
//фаза саранчи //фаза саранчи
if (!jsonObjSub.isNull("phaseEvolutionName")) if(!jsonObjSub.isNull("phaseEvolutionName") && !jsonObjSub.optString("phaseEvolutionName","").isBlank()) {
locust.phase = jsonObjSub.getString("phaseEvolutionName"); locust.phase = jsonObjSub.getString("phaseEvolutionName");
switch (jsonObjSub.optString("phaseEvolutionName",null).replace("'", "").trim()) {
case "Кубышка":
locust.locust_have = "2"; //Кубышка = Яйца
break;
case "Гусеница","Личинка","Личинка 2-го возраста","Личинка 3-го возраста","Личинка 4-го возраста","Личинка 5-го возраста":
locust.locust_have = "3"; locust.locust_have = "3";
if (locust.phase != null) { break;
if (locust.phase.equals("Кубышка")) locust.locust_have = "2"; //Кубышка = Яйца case "Кулиги":
if (locust.phase.equals("Гусеница")) locust.locust_have = "3"; locust.locust_have = "4";
if (locust.phase.equals("Личинка 2-го возраста")) locust.locust_have = "3"; break;
if (locust.phase.equals("Личинка 3-го возраста")) locust.locust_have = "3"; case "Имаго":
if (locust.phase.equals("Личинка 4-го возраста")) locust.locust_have = "3"; locust.locust_have = "5";
if (locust.phase.equals("Личинка 5-го возраста")) locust.locust_have = "3"; break;
if (locust.phase.equals("Имаго")) locust.locust_have = "5"; default:
throw new CustomException(200, 10000, "Not find phaseEvolutionName: (" + locust.phase+")", null, true);
}
}else{
throw new CustomException(200, 10000, "Field phaseEvolutionName is null", null, true);
} }
if(!jsonObjSub.isNull("subPestCount") && !jsonObjSub.optString("subPestCount","").isBlank()) {
switch (locust.locust_have) {
//Если эта анкета "Имаго" то записываем плотность имаго на m2 case "5": //Если эта анкета "Имаго" то записываем плотность имаго на m2
if (locust.locust_have.equals("5")) {
if (!jsonObjSub.isNull("subPestCount"))
locust.imago_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); locust.imago_density = String.valueOf(jsonObjSub.getFloat("subPestCount"));
} break;
//Если эта анкета "Кубышка"="Яйца" то записываем плотность кулиг на m2 case "2": //Если эта анкета "Кубышка"="Яйца" то записываем плотность кулиг на m2
if (locust.locust_have.equals("2")) {
if (!jsonObjSub.isNull("subPestCount"))
locust.eggs_capsules_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); locust.eggs_capsules_density = String.valueOf(jsonObjSub.getFloat("subPestCount"));
} break;
//Если эта анкета "Кулиги" то записываем плотность кулиг на m2 case "4": //Если эта анкета "Кулиги" то записываем плотность кулиг на m2
if (locust.locust_have.equals("4")) {
if (!jsonObjSub.isNull("subPestCount"))
locust.kuliguli_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); locust.kuliguli_density = String.valueOf(jsonObjSub.getFloat("subPestCount"));
} break;
//Если эта анкета "Личинок" то записываем плотность личинок на m2 case "3": //Если эта анкета "Личинок" то записываем плотность личинок на m2
if (locust.locust_have.equals("3")) {
if (!jsonObjSub.isNull("subPestCount"))
locust.larva_density = String.valueOf(jsonObjSub.getFloat("subPestCount")); locust.larva_density = String.valueOf(jsonObjSub.getFloat("subPestCount"));
break;
default:
throw new CustomException(200, 10000, "Not set subPestCount: (" + locust.locust_have+")", null, true);
} }
}//else{
// throw new CustomException(200, 10000, "Field subPestCount is null", null, true);
//}
//Биотоп //Биотоп
if(!jsonObjSub.isNull("faoBiotopeName") && !jsonObjSub.optString("faoBiotopeName","").isBlank()) {
switch (jsonObjSub.getString("faoBiotopeName")) { switch (jsonObjSub.getString("faoBiotopeName")) {
case "CIT степь": case "CIT степь":
locust.bio_biotope_id = "1"; locust.bio_biotope_id = "1";
@ -1044,27 +957,13 @@ public class AcceptJSON implements ServletContextAware {
locust.bio_biotope_id = "18"; locust.bio_biotope_id = "18";
break; break;
default: default:
locust.bio_biotope_id = null; throw new CustomException(200, 10000, "Not set faoBiotopeName: (" + jsonObjSub.getString("faoBiotopeName")+")", null, true);
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{ }else{
throw new CustomException(200, 10000, "Field faoBiotopeName is null", null, true);
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 { try {
locust.description = ""; locust.description = "";
@ -1082,209 +981,72 @@ public class AcceptJSON implements ServletContextAware {
locust.description += "\n"; locust.description += "\n";
} }
if (!jsonObj.isNull("cropCurrentType")) if (!jsonObjSub.isNull("cropCurrentType"))
locust.description += "Тип сева: " + jsonObj.getString("cropCurrentType") + "\n"; locust.description += "Тип сева: " + jsonObjSub.getString("cropCurrentType") + "\n";
if (!jsonObj.isNull("cropCurrentCulture")) if (!jsonObjSub.isNull("cropCurrentCulture"))
locust.description += "Наименование культуры: " + jsonObj.getString("cropCurrentCulture") + "\n"; locust.description += "Наименование культуры: " + jsonObjSub.getString("cropCurrentCulture") + "\n";
if (!jsonObj.isNull("cropCurrentCultureSort")) if (!jsonObjSub.isNull("cropCurrentCultureSort"))
locust.description += "Наименование сорта культуры: " + jsonObj.getString("cropCurrentCultureSort") + "\n"; locust.description += "Наименование сорта культуры: " + jsonObjSub.getString("cropCurrentCultureSort") + "\n";
if (!jsonObj.isNull("cropCurrentGrowthPhase")) if (!jsonObjSub.isNull("cropCurrentGrowthPhase"))
locust.description += "Фаза роста культуры: " + jsonObj.getString("cropCurrentGrowthPhase") + "\n"; locust.description += "Фаза роста культуры: " + jsonObjSub.getString("cropCurrentGrowthPhase") + "\n";
if (!jsonObj.isNull("cropFieldArea")) { if (!jsonObjSub.isNull("cropFieldArea")) {
locust.description += "Площадь поля: " + jsonObj.getFloat("cropFieldArea") + "\n"; locust.description += "Площадь поля: " + jsonObjSub.getFloat("cropFieldArea") + "\n";
locust.bio_hectare = String.valueOf(jsonObj.getFloat("cropFieldArea")); locust.bio_hectare = String.valueOf(jsonObjSub.getFloat("cropFieldArea"));
} }
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); throw new CustomException(200, 10000, "Error: " +ex.getMessage(), null, true);
} }
locust.terrain = "null"; //У росиян нет сельского округа locust.terrain = "null"; //У Россиян нет сельского округа
row = "<tr>"; //Если те виды вредителей что нам нужны
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()) { if(!(
row = "<tr style=\"background-color:red;\">"; jsonObj.isNull("regionName") ||
} jsonObj.getString("regionName").isEmpty() ||
row += "<td>" + String.valueOf(cntO+cntV) + "</td><td>" + locust.eid + "</td><td>" + locust.lat_center + "</td><td>" + locust.lon_center + "</td><td>" + regionName + " = " + locust.region_id + "</td><td>" + locust.district + " = " + locust.district_id + "</td><td>" + locust.terrain + "</td><td>" + locust.village + "</td><td>" + locust.locust + " = " + locust.locust_type_id + "</td><td>" + locust.phase + " = " + locust.locust_have + "</td><td>" + locust.evp + "</td><td>" + locust.size + " = " + locust.drawPolygon + "</td><td>" + locust.date + "</td>"; locust.lat_center == null ||
row += "</tr>\n"; 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("Бахчевая коровка")
)) {
//Если записи не существует то вставляем если существует то обновляем //I check if there is already such a record in the database, if not, I insert it, if there is, I update it
boolean exists = false; //Is there a record. UpdateLocust updateLocust = new UpdateLocust(jdbcTemplate);
Statement st; if(updateLocust.update(locust))
try { count++;
st = conn.createStatement(); System.out.println("Count = "+count);
//ResultSet rs=null;
try {
sql = "select 1 from main.frmlocust where eid=" + String.valueOf(locust.eid);
rs = st.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace();
model.addAttribute("PreviewTable", "Error select");
return "json";
}
if (rs != null) {
if (rs.next())
exists = true;
}
st.close();
} catch (SQLException ex) {
ex.printStackTrace();
model.addAttribute("PreviewTable", "Error select 2");
return "json";
}
PreparedStatement stmt = null; //Downloading photos from locust survey forms
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.setTimestamp(8, locust.date);
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(); sb = new StringBuilder();
try { try {
String strURL = "https://rscagex.ru/pmon/rest/getPhotosByParentId?token=QVOUE97HBSI6LBSGJGQZMP3KPSS1QK&parentId=" + locust.eid; String strURL = "https://rscagex.ru/pmon/rest/getPhotosByParentId?token=QVOUE97HBSI6LBSGJGQZMP3KPSS1QK&parentId=" + locust.eid;
URL url = new URL(strURL); URI uri = new URI(strURL);
URL url = uri.toURL();
HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("GET"); hConn.setRequestMethod("GET");
//hConn.setRequestProperty("Range","bytes=" + posStart + "-" + posEnd);
hConn.connect(); hConn.connect();
int responseCode = hConn.getResponseCode(); int responseCode = hConn.getResponseCode();
if (responseCode / 100 == 2) //Code 206 is "Partial Content" if (responseCode / 100 == 2) //Code 206 is "Partial Content"
{ {
InputStream inputStream = hConn.getInputStream(); InputStream inputStream = hConn.getInputStream();
//FileOutputStream outputStream = new FileOutputStream(strFile);
int bytesRead; int bytesRead;
byte[] buffer = new byte[BUFFER_SIZE]; byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) { while ((bytesRead = inputStream.read(buffer)) != -1) {
//outputStream.write(buffer, 0, bytesRead);
sb.append(new String(buffer, 0, bytesRead)); sb.append(new String(buffer, 0, bytesRead));
} }
//outputStream.close();
inputStream.close(); inputStream.close();
} }
hConn.disconnect(); hConn.disconnect();
@ -1294,12 +1056,12 @@ public class AcceptJSON implements ServletContextAware {
String base64 = sb.toString(); String base64 = sb.toString();
if (base64.length() > 10) { if (base64.length() > 10) {
//Так как мне присылаю неправильный jSOM то пытаюсь его поправить,. //Trying to fix the malformed JSON string received in base64 format...
base64 = base64.replace("[", "[\""); base64 = base64.replace("[", "[\"");
base64 = base64.replace("]", "\"]"); base64 = base64.replace("]", "\"]");
base64 = base64.replace(", ", "\",\""); base64 = base64.replace(", ", "\",\"");
String strFile = "O:\\temp\\CCALM\\ru_" + locust.eid; String strFile = data_dir + "data/frmlocust/ru_" + locust.eid; //First pat of file name
int pos = 0; int pos = 0;
JSONArray jsonArrayIMGS = new JSONArray(base64); JSONArray jsonArrayIMGS = new JSONArray(base64);
@ -1308,14 +1070,6 @@ public class AcceptJSON implements ServletContextAware {
pos++; pos++;
if (pos > 3) break; 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; byte[] decodedString = null;
try { try {
decodedString = Base64.getDecoder().decode(jsonObjIMG); decodedString = Base64.getDecoder().decode(jsonObjIMG);
@ -1353,74 +1107,49 @@ public class AcceptJSON implements ServletContextAware {
buffered.getGraphics().drawImage(img, 0, 0, null); buffered.getGraphics().drawImage(img, 0, 0, null);
} }
try { try {
//BufferedImage bIMG = toBufferedImage(img);
ImageIO.write(buffered, "jpg", new File(strFile + "_" + pos + ".jpg")); ImageIO.write(buffered, "jpg", new File(strFile + "_" + pos + ".jpg"));
} catch (IOException ex) { } catch (IOException ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
if (pos > 3) {
break;
} else {
sql = ""; sql = "";
if (pos == 1) { if (pos == 1) {
sql = "update main.frmlocust set image_name1='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; sql = "update main.frmlocust set image_name1=:image_name where eid=:eid";
} }
if (pos == 2) { if (pos == 2) {
sql = "update main.frmlocust set image_name2='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; sql = "update main.frmlocust set image_name2=:image_name where eid=:eid";
} }
if (pos == 3) { if (pos == 3) {
sql = "update main.frmlocust set image_name3='ru_" + locust.eid + "_" + pos + ".jpg" + "' where eid=" + locust.eid; sql = "update main.frmlocust set image_name3=:image_name where eid=: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";
}
}
} }
MapSqlParameterSource insertParams = new MapSqlParameterSource();
insertParams.addValue("image_name", "ru_" + locust.eid + "_" + pos + ".jpg", Types.VARCHAR);
insertParams.addValue("eid", locust.eid, Types.INTEGER);
jdbcTemplate.update(sql, insertParams);
} }
} }
} }
} //equals("Вредители") } //equals("Вредители")
}
}
table += row;
}
System.out.println("Обработка = "+String.valueOf(cntO));
System.out.println("Вредители = "+String.valueOf(cntV));
table += "</table>";
//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) {
model.addAttribute("PreviewTable", "Error update img");
throw new CustomException(200, 10000, ex.getMessage(),null,true);
} }
} }
} }
model.addAttribute("PreviewTable",table);
//model.addAttribute("PreviewGEOJSON",json); //Save last download date
model.addAttribute("PreviewSQL",sqlData); String insertSql = """
insert into integration.days_ru(date, count) values (:date, :count)
""";
MapSqlParameterSource insertParams = new MapSqlParameterSource();
insertParams.addValue("date", lastDate, Types.DATE);
insertParams.addValue("count", count, Types.INTEGER);
jdbcTemplate.update(insertSql, insertParams);
}
}
model.addAttribute("PreviewTable","");
model.addAttribute("PreviewSQL","");
} catch (CustomException e) { } catch (CustomException e) {
if(e.isSaveToLog()) { if(e.isSaveToLog()) {
@ -1431,7 +1160,7 @@ public class AcceptJSON implements ServletContextAware {
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
logger.error(MarkerFactory.getMarker(uuid), ex.getMessage(), ex); logger.error(MarkerFactory.getMarker(uuid), ex.getMessage(), ex);
} }
return "json"; return json.toString();
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
//https://127.0.0.1:8083/AcceptJSON_UZB //https://127.0.0.1:8083/AcceptJSON_UZB

View File

@ -1,25 +0,0 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Select the file with CSV to upload and parsing.</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<form action="./AcceptJSON" method="post" enctype="multipart/form-data">
Select CSV UTF-8 file to upload and export:
<input type="file" name="file" id="fileToUpload"><br>
<input type="submit" value="Upload" name="submit">
</form>
<br><br>
${PreviewTable}
<!--br><br><br>
<textarea style="width: 1000px;height: 1000px;">${PreviewGEOJSON}</textarea>
<br><br><br>
<textarea style="width: 1400px;height: 1000px;">${PreviewSQL}</textarea-->
</body>
</html>