diff --git a/src/main/java/org/ccalm/main/AcceptASDCController.java b/src/main/java/org/ccalm/main/AcceptASDCController.java index f3de8a7..fb12079 100644 --- a/src/main/java/org/ccalm/main/AcceptASDCController.java +++ b/src/main/java/org/ccalm/main/AcceptASDCController.java @@ -1707,7 +1707,7 @@ public class AcceptASDCController implements ServletContextAware { String imgDir="./data/frmlocust/"; try{ new File(dataDir+imgDir).mkdirs(); }catch (Exception exception) {} - if(image_name1!=null && !image_name1.equals("")) + if(image_name1!=null && !image_name1.isEmpty()) { String filename1=dataDir+tmpDir+image_name1; File f = new File(filename1); @@ -1715,7 +1715,7 @@ public class AcceptASDCController implements ServletContextAware { f.renameTo(new File(dataDir+imgDir+image_name1)); } } - if(image_name2!=null && !image_name2.equals("")) + if(image_name2!=null && !image_name2.isEmpty()) { String filename2=dataDir+tmpDir+image_name2; File f = new File(filename2); @@ -1723,7 +1723,7 @@ public class AcceptASDCController implements ServletContextAware { f.renameTo(new File(dataDir+imgDir+image_name2)); } } - if(image_name3!=null && !image_name3.equals("")) + if(image_name3!=null && !image_name3.isEmpty()) { String filename3=dataDir+tmpDir+image_name3; File f = new File(filename3); @@ -2453,7 +2453,7 @@ public class AcceptASDCController implements ServletContextAware { //If there are drawings, then copy them. String imgDir="./data/frmlocustdel/"; try{ new File(dataDir+imgDir).mkdirs(); }catch (Exception exception) {} - if(image_name1!=null && !image_name1.equals("")) + if(image_name1!=null && !image_name1.isEmpty()) { String filename1=dataDir+tmpDir+image_name1; File f = new File(filename1); @@ -2461,7 +2461,7 @@ public class AcceptASDCController implements ServletContextAware { f.renameTo(new File(dataDir+imgDir+image_name1)); } } - if(image_name2!=null && !image_name2.equals("")) + if(image_name2!=null && !image_name2.isEmpty()) { String filename2=dataDir+tmpDir+image_name2; File f = new File(filename2); @@ -2469,7 +2469,7 @@ public class AcceptASDCController implements ServletContextAware { f.renameTo(new File(dataDir+imgDir+image_name2)); } } - if(image_name3!=null && !image_name3.equals("")) + if(image_name3!=null && !image_name3.isEmpty()) { String filename3=dataDir+tmpDir+image_name3; File f = new File(filename3); @@ -2859,7 +2859,7 @@ public class AcceptASDCController implements ServletContextAware { //Проверка на существование полей в обеих таблицах ExistsType[] fb=new ExistsType[tbl.fields.size()]; - Map col = TCTableTools.getTableSchema(conn, "main" + tbl.name); + Map col = TCTableTools.getTableSchema(conn, "main."+tbl.name); for(int i=0;i"; } row+=""+i+""+locust.lat+""+locust.lon+""+locust.region+" = "+locust.region_id+""+locust.district+" = "+locust.district_id+""+locust.terrain+""+locust.village+""+locust.locust+" = "+locust.locust_id+""+locust.phase+" = "+locust.locust_have+""+locust.evp+""+locust.size+""+locust.date+""; diff --git a/src/main/java/org/ccalm/main/AcceptJSON.java b/src/main/java/org/ccalm/main/AcceptJSON.java index 6def497..2dff9bf 100644 --- a/src/main/java/org/ccalm/main/AcceptJSON.java +++ b/src/main/java/org/ccalm/main/AcceptJSON.java @@ -145,7 +145,7 @@ public class AcceptJSON implements ServletContextAware { int year=2024; int cnt=0; - if(content==null || content.equals("")) { + if(content==null || content.isEmpty()) { System.out.println("Content is null"); }else { System.out.println("Start"); @@ -499,7 +499,7 @@ public class AcceptJSON implements ServletContextAware { e.printStackTrace(); } String content=sb.toString(); - if(content!=null && !content.equals("")) { + if(content!=null && !content.isEmpty()) { //byte[] data = sb.toByteArray(in); //String content=new String(data, Charsets.UTF_8); @@ -576,7 +576,7 @@ public class AcceptJSON implements ServletContextAware { } - /*if(locust.region_id.equals("")){ + /*if(locust.region_id.isEmpty()){ if(locust.region.indexOf("Воронежс��ая область")>=0) locust.region_id="110"; if(locust.region.indexOf("Кра��нодарский край")>=0) locust.region_id="164"; if(locust.region.indexOf("Астраха��ская область")>=0) locust.region_id="68"; //dayOfYear: 97 at year: 2022 = 07.04.2022 @@ -708,7 +708,7 @@ public class AcceptJSON implements ServletContextAware { if (!jsonObjSub.isNull("agroTreatmentType")) { String agroTreatmentType = jsonObjSub.getString("agroTreatmentType"); //Тип обработки (Агротехнический, Авиационный, Наземный) - if (agroTreatmentType != null && !agroTreatmentType.equals("")) { + if (agroTreatmentType != null && !agroTreatmentType.isEmpty()) { if (agroTreatmentType.equals("GROUND")) { locust.spray_platform = "3"; } else if (agroTreatmentType.equals("AGROTECHNICAL")) { @@ -717,7 +717,7 @@ public class AcceptJSON implements ServletContextAware { locust.spray_platform = "1"; } } - if (locust.spray_platform == null || locust.spray_platform.equals("")) { + if (locust.spray_platform == null || locust.spray_platform.isEmpty()) { model.addAttribute("PreviewTable", "Error spray_platform"); return "json"; } @@ -842,12 +842,12 @@ public class AcceptJSON implements ServletContextAware { stmt.setString(11, locust.insecticide_name); stmt.setString(12, locust.insecticide_active_substance); - if (locust.insecticide_dose == null || locust.insecticide_dose.equals("")) + 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.equals("")) + if (locust.spray_platform == null || locust.spray_platform.isEmpty()) stmt.setNull(14, Types.INTEGER); else stmt.setInt(14, Integer.parseInt(locust.spray_platform)); @@ -994,17 +994,17 @@ public class AcceptJSON implements ServletContextAware { } //Если те виды что нам нужны - if (locust.region == null || locust.region.equals("") || locust.lat == 0 || locust.lon == 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("Бахчевая коровка")) { + if (locust.region == null || locust.region.isEmpty() || locust.lat == 0 || locust.lon == 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_id.equals("")) { + if (locust.locust_id.isEmpty()) { System.out.println("locust.locust = "+locust.locust); model.addAttribute("PreviewTable", "locust.locust_id == 0 locust name = " + locust.locust); logger.error("Error, not find locust.locust = "+locust.locust); return "json"; } - if (locust.region_id.equals("")) { + if (locust.region_id.isEmpty()) { System.out.println("locust.region = "+locust.region); model.addAttribute("PreviewTable", "locust.region_id == 0 region name = " + locust.region); logger.error("Error, not find locust.region = "+locust.region); @@ -1050,7 +1050,7 @@ public class AcceptJSON implements ServletContextAware { locust.terrain = "null"; //У росиян нет сельского округа row = ""; - if (locust.region_id == null || locust.region_id.equals("") || locust.district_id == null || locust.district_id.equals("") || locust.locust_id == null || locust.locust_id.equals("")) { + if (locust.region_id == null || locust.region_id.isEmpty() || locust.district_id == null || locust.district_id.isEmpty() || locust.locust_id == null || locust.locust_id.isEmpty()) { row = ""; } row += "" + String.valueOf(cntO+cntV) + "" + locust.eid + "" + locust.lat + "" + locust.lon + "" + locust.region + " = " + locust.region_id + "" + locust.district + " = " + locust.district_id + "" + locust.terrain + "" + locust.village + "" + locust.locust + " = " + locust.locust_id + "" + locust.phase + " = " + locust.locust_have + "" + locust.evp + "" + locust.size + " = " + locust.drawPolygon + "" + locust.date + ""; @@ -1373,6 +1373,980 @@ public class AcceptJSON implements ServletContextAware { return "json"; } //--------------------------------------------------------------------------- + @ResponseBody + @RequestMapping(value = "/AcceptJSON_UZB", method = { RequestMethod.GET, RequestMethod.POST }) + public String acceptUZB(@ModelAttribute User user) { + + Connection conn = null; + try { + Class.forName("org.postgresql.Driver"); + conn = DriverManager.getConnection(db_url, db_login, db_password); + } catch (Exception ex) { + ex.printStackTrace(); + return "{\"error_code\":10000}"; + } + + //Set UTC time + Statement stm=null; + try { + stm = conn.createStatement(); + try { + stm.execute("SET timezone TO 'UTC';"); + } catch( SQLException ex ) { + ex.printStackTrace(); + } + 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_uz"); + if (rs != null) { + try { + if (rs.next()) { + String value = rs.getString(1); + if(value!=null) + lastDate = LocalDate.parse(value); + } + 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(lastDate==null) lastDate = LocalDate.parse("2024-10-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); + + String dateBegin=lastDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); + String dateEnd=dateBegin; + + System.out.println( "date = " + dateEnd ); + + //Download JSON data from server + StringBuilder sb = new StringBuilder(); + try + { + String strURL="https://locust.uz/api/integration/ccalm/survey-list/?recorded_date_gte="+dateBegin+"&recorded_date_lte="+dateEnd; + + URL url = new URL(strURL); + HttpURLConnection hConn = (HttpURLConnection) url.openConnection(); + hConn.setRequestMethod("GET"); + hConn.setRequestProperty("Accept", "application/json"); + 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(); + } + hConn.disconnect(); + } + catch (IOException e) + { + e.printStackTrace(); + } + String content=sb.toString(); + if(content!=null && !content.isEmpty()) { + + //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; + Locust locust = new Locust(); + + locust.date = jsonObj.getString("date"); + + if (!jsonObj.isNull("region_name")) + locust.region = jsonObj.getString("region_name"); + else + locust.region = ""; + + if (!jsonObj.isNull("town_name")) + locust.district = jsonObj.getString("town_name"); + + if (!jsonObj.isNull("point")) { + locust.lon = jsonObj.getJSONObject("point").getJSONArray("coordinates").getDouble(0); + locust.lat = 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 (locust.region.length() > 0) { + //Выбираю 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 '%" + locust.region + "%';"; + 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(locust.region_id.isEmpty()){ + if(locust.region.indexOf("Воронежс��ая область")>=0) locust.region_id="110"; + if(locust.region.indexOf("Кра��нодарский край")>=0) locust.region_id="164"; + if(locust.region.indexOf("Астраха��ская область")>=0) locust.region_id="68"; //dayOfYear: 97 at year: 2022 = 07.04.2022 + if(locust.region.indexOf("Астраханская област��")>=0) locust.region_id="68"; // dayOfYear: 101 at year: 2022 = 11.04.2022 + }*/ + + if (locust.region_id.length() > 0) { + //Выбираю id региона (main.countriesdistricts) + locust.district_id = ""; + stt = null; + 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 + "%';"; + rs = stt.executeQuery(sql_query); + if (rs != null) { + try { + if (rs.next()) { + locust.district_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(); + } + } + } + } + + String row = ""; + + if (!jsonObj.isNull("subjectList")) { + JSONArray jsonArraySub = jsonObj.getJSONArray("subjectList"); + + for (Object o2 : jsonArraySub) { + JSONObject jsonObjSub = (JSONObject) o2; + + locust.eid = 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; + 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 (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 { + stmt.setInt(1, locust.eid); + stmt.setDouble(2, locust.lat); + stmt.setDouble(3, locust.lon); + 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_id = ""; + if (locust.locust.equals("Короткокрылый зеленчук")) locust.locust_id = "4"; + if (locust.locust.equals("Среднерусская перелётная саранча")) locust.locust_id = "4"; + if (locust.locust.equals("Сибирская кобылка")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка изменчивая")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка пёстрая")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка крестовая")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка сибирская")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка голубокрылая")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка бескрылая")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка чернополосая")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка трескучая")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка египетская")) locust.locust_id = "4"; + if (locust.locust.equals("Трещотка ширококрылая")) locust.locust_id = "4"; + if (locust.locust.equals("Бахчевая кобылка")) locust.locust_id = "4"; + if (locust.locust.equals("Малая крестовичка")) locust.locust_id = "4"; + if (locust.locust.equals("Конёк белополосый (белополосая кобылка)")) + locust.locust_id = "4"; + if (locust.locust.equals("Конек обыкновенный")) locust.locust_id = "4"; + if (locust.locust.equals("Конек обыкновенный")) locust.locust_id = "4"; + if (locust.locust.equals("Кобылка темнокрылая")) locust.locust_id = "4"; + if (locust.locust.equals("Краснокрылая кобылка")) locust.locust_id = "4"; + if (locust.locust.equals("Краснокрылая кобылка")) locust.locust_id = "4"; + if (locust.locust.equals("Степная кобылка")) locust.locust_id = "4"; + if (locust.locust.equals("Гребневка")) locust.locust_id = "4"; + if (locust.locust.equals("Азиатская перелётная саранча")) locust.locust_id = "3"; + if (locust.locust.equals("Итальянский прус")) locust.locust_id = "1"; + if (locust.locust.equals("Мароккская саранча, мароккская кобылка, марокканка")) + locust.locust_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 (locust.region == null || locust.region.isEmpty() || locust.lat == 0 || locust.lon == 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_id.isEmpty()) { + System.out.println("locust.locust = "+locust.locust); + //model.addAttribute("PreviewTable", "locust.locust_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 = "+locust.region); + //model.addAttribute("PreviewTable", "locust.region_id == 0 region name = " + locust.region); + logger.error("Error, not find locust.region = "+locust.region); + 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"; + } + + 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_id == null || locust.locust_id.isEmpty()) { + row = ""; + } + row += ""; + row += "\n"; + + //Если записи не существует то вставляем если существует то обновляем + boolean exists = false; //Is there a record. + Statement st; + try { + st = conn.createStatement(); + //ResultSet rs=null; + try { + String 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; + String 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.setInt(1, locust.eid); + stmt.setDouble(2, locust.lat); + stmt.setDouble(3, locust.lon); + 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_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 { + 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(); + } + 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) { + try { + st = conn.createStatement(); + st.execute(sql); + st.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + //model.addAttribute("PreviewTable", "Error update img"); + return "json"; + } + } + } + } + } + } + + } //equals("Вредители") + + } + + } + + table += row; + } + 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 + "" + locust.lon + "" + locust.region + " = " + locust.region_id + "" + locust.district + " = " + locust.district_id + "" + locust.terrain + "" + locust.village + "" + locust.locust + " = " + locust.locust_id + "" + locust.phase + " = " + locust.locust_have + "" + locust.evp + "" + locust.size + " = " + locust.drawPolygon + "" + locust.date + "
"; + + //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"; + } + } + } + //model.addAttribute("PreviewTable",table); + //model.addAttribute("PreviewGEOJSON",json); + //model.addAttribute("PreviewSQL",sqlData); + + return "json"; + } + //--------------------------------------------------------------------------- public static BufferedImage toBufferedImage(Image img) { if (img instanceof BufferedImage) diff --git a/src/main/java/org/ccalm/main/DataJSON.java b/src/main/java/org/ccalm/main/DataJSON.java index 0415574..a0af76f 100644 --- a/src/main/java/org/ccalm/main/DataJSON.java +++ b/src/main/java/org/ccalm/main/DataJSON.java @@ -109,7 +109,7 @@ public class DataJSON implements ServletContextAware { sql_query = "select id,name from main.companies where del=false and name is not null and name!='' and (${country_id} is null or country_id=${country_id})"; PreparedStatementNamed stmtn = new PreparedStatementNamed(conn, sql_query); - if(country_id==null || country_id.equals("")) + if(country_id==null || country_id.isEmpty()) stmtn.setNULLInt("country_id"); else stmtn.setInt("country_id",Integer.parseInt(country_id)); diff --git a/src/main/java/org/ccalm/main/DownloadNDVI.java b/src/main/java/org/ccalm/main/DownloadNDVI.java index 7e2fc88..a0c8485 100644 --- a/src/main/java/org/ccalm/main/DownloadNDVI.java +++ b/src/main/java/org/ccalm/main/DownloadNDVI.java @@ -145,7 +145,7 @@ public class DownloadNDVI implements ServletContextAware { logger.info(ex.getMessage()); result+=ex.getMessage()+"
"; } - if(!strPos1.equals("")) + if(!strPos1.isEmpty()) { //String strPos1 = "250:146339365:d=2017022818:TSOIL:0-0.1 m below ground:anl:" StringBuffer answer1=new StringBuffer(strPos1); @@ -155,7 +155,7 @@ public class DownloadNDVI implements ServletContextAware { StringBuffer answer2=new StringBuffer(strPos2); CutBeforeFirst(answer2,":"); String posEnd = CutBeforeFirst(answer2,":"); - if(posEnd==null || posEnd.equals("")) posEnd=""; else + if(posEnd==null || posEnd.isEmpty()) posEnd=""; else { posEnd=String.valueOf(Long.parseLong(posEnd)-1); } @@ -275,7 +275,7 @@ public class DownloadNDVI implements ServletContextAware { logger.info(ex.getMessage()); } } - if(country_id!=null && !country_id.equals("") && !country_id.equals("null")) + if(country_id!=null && !country_id.isEmpty() && !country_id.equals("null")) { //logger.info(lon + "," + lat +","+dataArrayTmp.getFloat(pos)); try { diff --git a/src/main/java/org/ccalm/main/DownloadWeather.java b/src/main/java/org/ccalm/main/DownloadWeather.java index b518a6b..729cf2d 100644 --- a/src/main/java/org/ccalm/main/DownloadWeather.java +++ b/src/main/java/org/ccalm/main/DownloadWeather.java @@ -91,7 +91,7 @@ public class DownloadWeather implements ServletContextAware { //Example request: http://ccalm.org/DownloadWeather?forecast=000&date=20210531 //Example request: http://localhost:8080/CCALM/DownloadWeather?forecast=000 //Example request: http://127.0.0.1:8080/CCALM/DownloadWeather?forecast=000 - if(date==null || date.equals("")) + if(date==null || date.isEmpty()) { DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); date=dateFormat.format(new Date()); //Date like as "20170327". @@ -138,7 +138,7 @@ public class DownloadWeather implements ServletContextAware { logger.info(ex.getMessage()); result+=ex.getMessage()+"
"; } - if(!strPos1.equals("")) + if(!strPos1.isEmpty()) { //String strPos1 = "250:146339365:d=2017022818:TSOIL:0-0.1 m below ground:anl:" StringBuffer answer1=new StringBuffer(strPos1); @@ -148,7 +148,7 @@ public class DownloadWeather implements ServletContextAware { StringBuffer answer2=new StringBuffer(strPos2); CutBeforeFirst(answer2,":"); String posEnd = CutBeforeFirst(answer2,":"); - if(posEnd==null || posEnd.equals("")) posEnd=""; else + if(posEnd==null || posEnd.isEmpty()) posEnd=""; else { posEnd=String.valueOf(Long.parseLong(posEnd)-1); } @@ -268,7 +268,7 @@ public class DownloadWeather implements ServletContextAware { logger.info(ex.getMessage()); } } - if(country_id!=null && !country_id.equals("") && !country_id.equals("null")) + if(country_id!=null && !country_id.isEmpty() && !country_id.equals("null")) { //logger.info(lon + "," + lat +","+dataArrayTmp.getFloat(pos)); try { diff --git a/src/main/java/org/ccalm/main/QGIS.java b/src/main/java/org/ccalm/main/QGIS.java index f502414..0453950 100644 --- a/src/main/java/org/ccalm/main/QGIS.java +++ b/src/main/java/org/ccalm/main/QGIS.java @@ -70,7 +70,7 @@ public class QGIS implements ServletContextAware { @ResponseBody public HttpEntity ajaxTamer(@ModelAttribute User user, @RequestParam(required=false,name="day") String day, @RequestParam(required=false,name="name") String name, @RequestParam(required=false,name="time") String time, @RequestParam(required=false,name="time_start") String time_start, @RequestParam(required=false,name="time_end") String time_end, @RequestParam(required=false,name="country_id") String country_id, @RequestParam(required=false,name="locust_type_id") String locust_type_id, @RequestParam(required=false,name="date_start") String date_start, @RequestParam(required=false,name="date_end") String date_end, @RequestParam(required=false,name="registered") String registered, @RequestParam(required=false,name="year") String year, @RequestParam(required=false,name="region_id") String region_id, @RequestParam(required=false,name="country_name") String country_name, @RequestParam(required=false,name="lng") String language_id, HttpServletResponse response) { - if(language_id!=null && !language_id.equals("")) user.language_id=language_id; + if(language_id!=null && !language_id.isEmpty()) user.language_id=language_id; logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id); m_locale=user.language_id; @@ -107,7 +107,7 @@ public class QGIS implements ServletContextAware { //Make SQL String sql = "1=1"; String sql2 = "1=1"; - if(country_id!=null && !country_id.equals("")) + if(country_id!=null && !country_id.isEmpty()) { if(country_id.equals("-1")) { @@ -123,15 +123,15 @@ public class QGIS implements ServletContextAware { sql2+=" and country_id="+country_id; } } - if(locust_type_id!=null && !locust_type_id.equals("")) + if(locust_type_id!=null && !locust_type_id.isEmpty()) { sql+=" and locust_type_id="+locust_type_id; } - if(date_start!=null && !date_start.equals("")) + if(date_start!=null && !date_start.isEmpty()) { sql+=" and date>='"+date_start+"'"; } - if(date_end!=null && !date_end.equals("")) + if(date_end!=null && !date_end.isEmpty()) { sql+=" and date<='"+date_end+"'"; } @@ -164,7 +164,7 @@ public class QGIS implements ServletContextAware { //Make SQL String sql = "1=1"; String sql2 = "1=1"; - if(country_id!=null && !country_id.equals("")) + if(country_id!=null && !country_id.isEmpty()) { //sql+=" and country_id="+country_id; if(country_id.equals("-1")) @@ -181,11 +181,11 @@ public class QGIS implements ServletContextAware { sql2+=" and country_id="+country_id; } } - if(date_start!=null && !date_start.equals("")) + if(date_start!=null && !date_start.isEmpty()) { sql+=" and date>='"+date_start+"'"; } - if(date_end!=null && !date_end.equals("")) + if(date_end!=null && !date_end.isEmpty()) { sql+=" and date<='"+date_end+"'"; } @@ -213,7 +213,7 @@ public class QGIS implements ServletContextAware { //Make SQL String sql = "1=1"; - if(country_id!=null && !country_id.equals("")) + if(country_id!=null && !country_id.isEmpty()) { if(country_id.equals("-1")) { @@ -226,7 +226,7 @@ public class QGIS implements ServletContextAware { sql+=" and country_id="+country_id; } } - if(locust_type_id!=null && !locust_type_id.equals("")) + if(locust_type_id!=null && !locust_type_id.isEmpty()) { sql+=" and locust_type_id="+locust_type_id; } @@ -245,11 +245,11 @@ public class QGIS implements ServletContextAware { //Make SQL String sql = "1=1"; - if(region_id!=null && !region_id.equals("")) + if(region_id!=null && !region_id.isEmpty()) { sql+=" and region_id="+region_id; } - if(locust_type_id!=null && !locust_type_id.equals("")) + if(locust_type_id!=null && !locust_type_id.isEmpty()) { sql+=" and locust_type_id="+locust_type_id; } @@ -263,7 +263,7 @@ public class QGIS implements ServletContextAware { { //Make SQL String sql2 = "1=1"; - if(country_id!=null && !country_id.equals("")) + if(country_id!=null && !country_id.isEmpty()) { if(country_id.equals("-1")) { @@ -287,7 +287,7 @@ public class QGIS implements ServletContextAware { { //Make SQL String sql2 = "1=1"; - if(country_id!=null && !country_id.equals("")) + if(country_id!=null && !country_id.isEmpty()) { if(country_id.equals("-1")) { @@ -311,7 +311,7 @@ public class QGIS implements ServletContextAware { { //Make SQL String sql2 = "1=1"; - if(country_id!=null && !country_id.equals("")) + if(country_id!=null && !country_id.isEmpty()) { if(country_id.equals("-1")) { @@ -335,7 +335,7 @@ public class QGIS implements ServletContextAware { { //Make SQL String sql2 = "1=1"; - if(country_id!=null && !country_id.equals("")) + if(country_id!=null && !country_id.isEmpty()) { if(country_id.equals("-1")) { @@ -457,7 +457,7 @@ public class QGIS implements ServletContextAware { if(st!=null) try{st.close();}catch(SQLException ex) {} if(rs!=null) try{rs.close();}catch(SQLException ex) {} } - if(result.equals("")) + if(result.isEmpty()) { result = Tools.replaceAll(key,"_", " "); } diff --git a/src/main/java/org/ccalm/main/SendMail.java b/src/main/java/org/ccalm/main/SendMail.java index 1ce2d6e..aa02e76 100644 --- a/src/main/java/org/ccalm/main/SendMail.java +++ b/src/main/java/org/ccalm/main/SendMail.java @@ -72,7 +72,7 @@ public class SendMail implements ServletContextAware { public Object send(@ModelAttribute User user,@RequestParam(required=false,name="lng") String language_id) { m_user = user; - if(language_id!=null && !language_id.equals("")) + if(language_id!=null && !language_id.isEmpty()) user.language_id=language_id; logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id+" user.country_id="+user.country_id); @@ -445,7 +445,7 @@ public class SendMail implements ServletContextAware { if(rs!=null) try{rs.close();}catch(SQLException ex) {} } } - if(result.equals("")) + if(result.isEmpty()) { result = key.replaceAll("_", " "); } diff --git a/src/main/java/org/ccalm/main/SendWarning.java b/src/main/java/org/ccalm/main/SendWarning.java index 16d0045..32333d3 100644 --- a/src/main/java/org/ccalm/main/SendWarning.java +++ b/src/main/java/org/ccalm/main/SendWarning.java @@ -4,6 +4,7 @@ import jakarta.servlet.ServletContext; import org.json.JSONObject; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.*; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; @@ -11,9 +12,15 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import tools.DBTools; +import tools.EmailUtility; +import tools.Translation; import tools.User; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; import java.sql.Types; +import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.*; @@ -21,6 +28,15 @@ import java.util.*; public class SendWarning { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SendWarning.class); + @Value("${mail.host}") + String mail_host = ""; + @Value("${mail.port}") + String mail_port = ""; + @Value("${mail.login}") + String mail_login = ""; + @Value("${mail.password}") + String mail_password = ""; + private final RestTemplate restTemplate = new RestTemplate(); private final NamedParameterJdbcTemplate jdbcTemplate; @@ -43,8 +59,7 @@ public class SendWarning { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity> entity = new HttpEntity<>(request, headers); - //String url = "https://geoserver2.ccalm.org/geodatalist/getAirTemperature"; - String url = "https://geoserver.ccalm.org/geodatalist/getAirTemperature"; + String url = "https://geoserver2.ccalm.org/geodatalist/getAirTemperature"; try { ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class); if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) { @@ -63,23 +78,30 @@ public class SendWarning { return result; } - @RequestMapping(value = "/api/main/v01/SendWarning",method = RequestMethod.GET,produces = "text/html;charset=UTF-8") + @RequestMapping(value = "/api/main/v01/SendWarning",method = RequestMethod.GET,produces = "application/json;charset=UTF-8") @ResponseBody - public ResponseEntity send(@ModelAttribute User user, @RequestParam(required=false,name="lng") String language_id) { + public ResponseEntity send() { Map result = new HashMap<>(); + result.put("error_code", 0); + try { String sql = """ select + t.uid, + t.user_uid, t.lat, t.lon, - t.temperature + t.temperature as value, + u.email, + l.short_name from main.frmcheckpoints t + join main._users u on u.uid=t.user_uid + join main._languages l on l.uid=u.language_uid where t.del=false and t.warn=true """; - MapSqlParameterSource parameters = new MapSqlParameterSource(); //parameters.addValue("language_id", language_id, Types.INTEGER); List ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper()); @@ -87,14 +109,68 @@ public class SendWarning { JSONObject obj = new JSONObject(jsonString); JSONObject tmp = getSoilTemperature(obj.getDouble("lat"),obj.getDouble("lon")); if(tmp!=null) { - double temperature = obj.getDouble("temperature"); - if (temperature < tmp.getDouble("val")) { - System.out.println(tmp.getDouble("val")); + Translation trt=new Translation(obj.getString("short_name"),jdbcTemplate); + double value = obj.getDouble("value"); + if (value < tmp.getDouble("value")) { + String email = obj.getString("email"); + if(email.equals("irigm@mail.ru") || email.equals("ivanov.i@istt.kz")){ //TODO для тестирования потом удалить + + StringBuilder html = new StringBuilder(); + html.append("") + .append("") + .append("") + .append("") + .append("") + .append("
") + .append("") // Логотип + .append("

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

") + .append("

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

") + .append("") + .append("") + .append("") + .append("
").append(trt.trt("Date")).append("").append(tmp.getString("date")).append("
").append(trt.trt("Value")).append("").append(tmp.getDouble("value")).append(" °C
") + .append(trt.trt("To_resume_monitoring_please_set_the_warn_field_to_true")) + .append("
") // Закрываем контейнер + .append("") + .append(""); + + boolean send = false; + try { + EmailUtility.sendEmail(mail_host, mail_port, mail_login, mail_password, email, trt.trt("Soil temperature"), html.toString()); + send = true; + } catch (Exception e) { + e.printStackTrace(); } + if(send) { + sql= """ + update + main.frmcheckpoints + set + warn=true + where uid=:uid + """; + MapSqlParameterSource param = new MapSqlParameterSource(); + param.addValue("uid", obj.getString("uid"), Types.INTEGER); + int rowsUpdated = jdbcTemplate.update(sql, param); + System.out.println("rowsUpdated = "+String.valueOf(rowsUpdated)); } } - + } + } + } + } catch (Exception e) { + String uuid = UUID.randomUUID().toString(); + logger.error(uuid,e); + } return new ResponseEntity<>(result, HttpStatus.OK); } - } diff --git a/src/main/java/org/ccalm/main/SessionController.java b/src/main/java/org/ccalm/main/SessionController.java index 21dd961..4dc3dc1 100644 --- a/src/main/java/org/ccalm/main/SessionController.java +++ b/src/main/java/org/ccalm/main/SessionController.java @@ -29,7 +29,7 @@ public class SessionController { //response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); JSONObject obj = new JSONObject(); - if(user.id==null || user.id.equals("") || user.id.equals("null")) + if(user.id==null || user.id.isEmpty() || user.id.equals("null")) obj.put("result", "ERROR"); else { obj.put("result", "OK"); diff --git a/src/main/java/org/ccalm/main/TranslationUtils.java b/src/main/java/org/ccalm/main/TranslationUtils.java index 594168e..3cfe82b 100644 --- a/src/main/java/org/ccalm/main/TranslationUtils.java +++ b/src/main/java/org/ccalm/main/TranslationUtils.java @@ -33,7 +33,7 @@ public class TranslationUtils { JSONObject obj = new JSONObject(jsonString); String key = obj.getString("identifier"); String val = obj.getString("translation"); - if (val.equals("")) { + if (val.isEmpty()) { val = val.replaceAll("_", " "); } model.addAttribute(key, val); diff --git a/src/main/java/org/ccalm/main/engine/EngineController.java b/src/main/java/org/ccalm/main/engine/EngineController.java index 2f96e1d..f76d235 100644 --- a/src/main/java/org/ccalm/main/engine/EngineController.java +++ b/src/main/java/org/ccalm/main/engine/EngineController.java @@ -108,7 +108,7 @@ public class EngineController implements ServletContextAware { return "redirect"; } - //if(language_id!=null && !language_id.equals("")) user.language_id=language_id; + //if(language_id!=null && !language_id.isEmpty()) user.language_id=language_id; //logger.info("user.id="+user.id+" user.name="+user.name+" user.language_id="+user.language_id); long country_id=0; @@ -153,10 +153,10 @@ public class EngineController implements ServletContextAware { String key = (String)k; String val=""; //val = trt(conn,key,user); //Если есть то перевод беру из базы данных - if(val.equals("")) + if(val.isEmpty()) { val = props.getProperty(key,""); - if(val.equals("")) + if(val.isEmpty()) { val = val.replaceAll("_", " "); } @@ -464,7 +464,7 @@ public class EngineController implements ServletContextAware { public String trt(Connection conn,String key,User user) { String result=""; - if(key.equals("")) + if(key.isEmpty()) return result; try { @@ -485,7 +485,7 @@ public class EngineController implements ServletContextAware { logger.info(ex.getMessage()); } - if(result.equals("")) + if(result.isEmpty()) { result = key.replaceAll("_", " "); } diff --git a/src/main/java/tools/PreparedStatementNamed.java b/src/main/java/tools/PreparedStatementNamed.java index f6830b6..14f91d7 100644 --- a/src/main/java/tools/PreparedStatementNamed.java +++ b/src/main/java/tools/PreparedStatementNamed.java @@ -91,7 +91,7 @@ public class PreparedStatementNamed { }else { for (int i = 0; i < fields.size(); i++) { if (fields.get(i).name.equals(name)) { - if (value.equals("0") || value.equals("false") || value.equals("")) + if (value.equals("0") || value.equals("false") || value.isEmpty()) m_prepStmt.setBoolean(fields.get(i).pos, false); else m_prepStmt.setBoolean(fields.get(i).pos, true); diff --git a/src/main/java/tools/Translation.java b/src/main/java/tools/Translation.java index faae615..ab31a7e 100644 --- a/src/main/java/tools/Translation.java +++ b/src/main/java/tools/Translation.java @@ -1,17 +1,17 @@ package tools; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.sql.*; +//import tools.dbtools.*; +import org.json.JSONArray; +import org.json.JSONObject; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import java.util.List; +import java.util.ArrayList; public class Translation { - - private static final Logger logger = LoggerFactory.getLogger(Translation.class); - public int language_id; - //public NamedParameterJdbcTemplate jdbcTemplate; - public Connection conn; - public Translation(String lng, Connection conn){ + public NamedParameterJdbcTemplate jdbcTemplate; + public Translation(String lng, NamedParameterJdbcTemplate jdbcTemplate){ language_id=1; switch (lng) { case "kz": @@ -29,12 +29,10 @@ public class Translation { language_id = 1; break; } - this.conn = conn; + this.jdbcTemplate = jdbcTemplate; } public String trt(String text){ - - boolean find = false; String sql = """ select translation @@ -42,39 +40,19 @@ public class Translation { main._translations where del=false - and language_id=${language_id} - and identifier=${identifier}; + and language_id=:language_id + and identifier=:identifier; """; - - PreparedStatementNamed stmtn=null; - try { - stmtn = new PreparedStatementNamed(conn, sql); - stmtn.setInt("language_id", language_id); - stmtn.setString("identifier", text); - } catch (SQLException e) { - logger.error("Error",e); - e.printStackTrace(); - } - - if(stmtn!=null){ - PreparedStatement stmt=stmtn.getPreparedStatement(); - ResultSet rs = null; - try { - rs = stmt.executeQuery(); - while (rs.next()) { - text = rs.getString(1); - find = true; + MapSqlParameterSource parameters = new MapSqlParameterSource(); + parameters.addValue("language_id", language_id); + parameters.addValue("identifier", text); + List ret = jdbcTemplate.query(sql, parameters, new tools.DBTools.JsonRowMapper()); + int i = 0; + for (i = 0; i < ret.size(); i++) { + JSONObject json = new JSONObject(ret.get(i)); + text = json.getString("translation"); } - } catch (SQLException e) { - logger.error("Error",e); - e.printStackTrace(); - }finally{ - try { if (rs != null) rs.close(); } catch (Exception e) {}; - try { if (stmt != null) stmt.close(); } catch (Exception e) {}; - } - } - - if(!find){ + if(i==0){ text = text.replace("_", " "); } return text;