Compare commits
10 Commits
7081e6ea20
...
715f9881a6
| Author | SHA1 | Date | |
|---|---|---|---|
| 715f9881a6 | |||
| b01d21d245 | |||
| 4cbc741fa9 | |||
| e043b80744 | |||
| a07332832a | |||
| 487fec663c | |||
| a63f90cd6d | |||
| 154b8c2767 | |||
| 29888de73b | |||
| 96b3c3ed1e |
@ -1,12 +1,17 @@
|
||||
server:
|
||||
port: 8081
|
||||
port: 8083
|
||||
ssl:
|
||||
key-store: classpath:keystore.jks
|
||||
key-store-password: QyKtWPZB
|
||||
key-store-type: JKS
|
||||
key-alias: weather
|
||||
servlet:
|
||||
session:
|
||||
timeout: 300s
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: kz_ccalm_weather
|
||||
name: org_ccalm_weather
|
||||
cache:
|
||||
type: none
|
||||
|
||||
@ -28,3 +33,10 @@ custom:
|
||||
login: postgres
|
||||
password: PasSecrKey1
|
||||
|
||||
|
||||
springdoc:
|
||||
api-docs:
|
||||
path: /api-docs
|
||||
swagger-ui:
|
||||
disable-swagger-default-url: true
|
||||
path: /myproject
|
||||
48
pom.xml
48
pom.xml
@ -5,12 +5,12 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.3.3</version>
|
||||
<version>3.4.2</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>org.ccalm</groupId>
|
||||
<artifactId>weather</artifactId>
|
||||
<version>0.0.7-SNAPSHOT</version>
|
||||
<version>0.0.9-SNAPSHOT</version>
|
||||
<name>weather</name>
|
||||
<description>Weather APP</description>
|
||||
<properties>
|
||||
@ -45,6 +45,30 @@
|
||||
<artifactId>logstash-logback-encoder</artifactId>
|
||||
<version>6.6</version>
|
||||
</dependency>
|
||||
<!--dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>20231013</version>
|
||||
</dependency-->
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>20240303</version>
|
||||
</dependency>
|
||||
<!-- Исключаю зависимость из другой библиотеки а то в логе конфликт -->
|
||||
<dependency>
|
||||
<groupId>com.vaadin.external.google</groupId>
|
||||
<artifactId>android-json</artifactId>
|
||||
<version>0.0.20131108.vaadin1</version>
|
||||
<scope>runtime</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/edu.ucar/netcdfAll -->
|
||||
<dependency>
|
||||
@ -53,6 +77,26 @@
|
||||
<version>5.3.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>2.6.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.webjars</groupId>
|
||||
<artifactId>webjars-locator</artifactId>
|
||||
<version>0.52</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.36</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
|
||||
@ -4,45 +4,36 @@ import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.sql.*;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.ccalm.weather.models.PointModel;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import tools.DBTools;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.context.ServletContextAware;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
//import main.DownloadFromHTTP;
|
||||
import org.ccalm.weather.WeatherDownload;
|
||||
import tctable.Tools;
|
||||
import tools.StdTools;
|
||||
import ucar.ma2.Array;
|
||||
import ucar.nc2.Dimension;
|
||||
import ucar.nc2.Variable;
|
||||
import ucar.nc2.dataset.NetcdfDataset;
|
||||
import org.json.JSONObject;
|
||||
|
||||
@Controller
|
||||
public class AirTemperature implements ServletContextAware {
|
||||
@ -74,16 +65,23 @@ public class AirTemperature implements ServletContextAware {
|
||||
}
|
||||
|
||||
//---------------------------------------------------------------------------
|
||||
public Connection getConn(String url, String login,String password){
|
||||
Connection conn = null;
|
||||
try{
|
||||
Class.forName("org.postgresql.Driver");
|
||||
conn = DriverManager.getConnection(url,login,password);
|
||||
}catch(Exception ex)
|
||||
{
|
||||
logger.error("N1: "+ex.getMessage()+"<br>",ex);
|
||||
public JSONObject createJSONError(int code, String message, String setting, String marker) {
|
||||
JSONObject json = new JSONObject();
|
||||
//try {
|
||||
json.put("error_code", code);
|
||||
if(message!=null && !message.isBlank()) {
|
||||
json.put("error_message", Arrays.asList(message));
|
||||
}
|
||||
return conn;
|
||||
if(setting!=null && !setting.isBlank()) {
|
||||
json.put("error_setting", Arrays.asList(setting));
|
||||
}
|
||||
if(marker!=null && !marker.isBlank()) {
|
||||
json.put("error_marker", marker);
|
||||
}
|
||||
//} catch (JSONException e) {
|
||||
// logger.error(e);
|
||||
//}
|
||||
return json;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
/**
|
||||
@ -105,11 +103,35 @@ public class AirTemperature implements ServletContextAware {
|
||||
if (!dir.exists()) dir.mkdirs();
|
||||
|
||||
//response.getWriter().append("Served at: ").append(request.getContextPath());
|
||||
Connection conn_all = getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_ru = getConn(db_url_ru,db_login_ru,db_password_ru);
|
||||
Connection conn_all = DBTools.getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_ru = DBTools.getConn(db_url_ru,db_login_ru,db_password_ru);
|
||||
Statement st_all=null;
|
||||
Statement st_ru=null;
|
||||
try {
|
||||
if(conn_all!=null) st_all = conn_all.createStatement();
|
||||
if(conn_ru!=null) st_ru = conn_ru.createStatement();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N3:"+ex.getMessage(),ex);
|
||||
}
|
||||
|
||||
//Example request: http://ccalm.org/AirTemperature?date=20210531
|
||||
//Example request: http://localhost:8080/AirTemperature?date=20210531
|
||||
//Example request: http://127.0.0.1:8080/AirTemperature?date=20210531
|
||||
if(date==null || date.equals(""))
|
||||
{
|
||||
//Если день не задан то ищем максимальный день не старше 10 дней и прибавляем 1 день
|
||||
String sql="select to_char(max(date)+'1 days'::interval, 'YYYYMMDD') from main.air_temperature_dates where hours=0 and date > now() - '10 days'::interval";
|
||||
if(st_all!=null) {
|
||||
try {
|
||||
try (ResultSet rs = st_all.executeQuery(sql)) {
|
||||
if (rs.next()) {
|
||||
date = rs.getString(1);
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N4:"+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(date==null || date.equals(""))
|
||||
{
|
||||
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
|
||||
@ -122,12 +144,18 @@ public class AirTemperature implements ServletContextAware {
|
||||
//Build URL to download
|
||||
String URL = "https://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/gfs."+date+"/"+time+"/atmos/gfs.t"+time+"z.pgrb2.0p25.f"+forecast;
|
||||
|
||||
File f = new File(data_dir+"temp"+File.separator+"air_text.idx");
|
||||
if(f.exists()) {
|
||||
if (!f.delete()) {
|
||||
File f1 = new File(data_dir+"temp"+File.separator+"air_text.idx");
|
||||
if(f1.exists()) {
|
||||
if (!f1.delete()) {
|
||||
System.out.println("Failed to delete the file \"air_text.idx\".");
|
||||
}
|
||||
}
|
||||
File f2 = new File(data_dir+"temp"+File.separator+"air_text.f000");
|
||||
if(f2.exists()) {
|
||||
if (!f2.delete()) {
|
||||
System.out.println("Failed to delete the file \"air_text.f000\".");
|
||||
}
|
||||
}
|
||||
|
||||
WeatherDownload wd = new WeatherDownload();
|
||||
if(wd.download(URL+".idx", data_dir+"temp"+File.separator+"air_text.idx", "0", ""))
|
||||
@ -157,12 +185,12 @@ public class AirTemperature implements ServletContextAware {
|
||||
if(!strPos1.isEmpty())
|
||||
{
|
||||
StringBuffer answer1=new StringBuffer(strPos1);
|
||||
CutBeforeFirst(answer1,":");
|
||||
String posStart = CutBeforeFirst(answer1,":");
|
||||
Tools.CutBeforeFirst(answer1,":");
|
||||
String posStart = Tools.CutBeforeFirst(answer1,":");
|
||||
|
||||
StringBuffer answer2=new StringBuffer(strPos2);
|
||||
CutBeforeFirst(answer2,":");
|
||||
String posEnd = CutBeforeFirst(answer2,":");
|
||||
Tools.CutBeforeFirst(answer2,":");
|
||||
String posEnd = Tools.CutBeforeFirst(answer2,":");
|
||||
if(posEnd==null || posEnd.equals("")) posEnd=""; else
|
||||
{
|
||||
posEnd=String.valueOf(Long.parseLong(posEnd)-1);
|
||||
@ -232,14 +260,6 @@ public class AirTemperature implements ServletContextAware {
|
||||
}
|
||||
dimIt = null;
|
||||
|
||||
Statement st_all=null;
|
||||
Statement st_ru=null;
|
||||
try {
|
||||
if(conn_all!=null) st_all = conn_all.createStatement();
|
||||
if(conn_ru!=null) st_ru = conn_ru.createStatement();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N3:"+ex.getMessage(),ex);
|
||||
}
|
||||
|
||||
try {
|
||||
String sql = "BEGIN TRANSACTION;";
|
||||
@ -292,6 +312,7 @@ public class AirTemperature implements ServletContextAware {
|
||||
}
|
||||
|
||||
int pos=0;
|
||||
try{
|
||||
for(int nLat=0;nLat<dataArrayLat.getSize();nLat++)
|
||||
{
|
||||
for(int nLon=0;nLon<dataArrayLon.getSize();nLon++)
|
||||
@ -317,52 +338,49 @@ public class AirTemperature implements ServletContextAware {
|
||||
if(!country_id.isEmpty()) db_ru=true;
|
||||
}
|
||||
|
||||
if(country_id!=null && !country_id.equals("") && !country_id.equals("null"))
|
||||
if(country_id!=null && !country_id.isEmpty() && !country_id.equals("null"))
|
||||
{
|
||||
String sql= """
|
||||
insert into main.air_temperature(
|
||||
val,
|
||||
country_id,
|
||||
point_id,
|
||||
air_temperature_date_id
|
||||
air_temperature_date_id,
|
||||
point_id
|
||||
)values(
|
||||
?,
|
||||
?,
|
||||
?,
|
||||
main.get_air_temperature_date(cast(to_timestamp(?, 'YYYYMMDD HH24') as timestamp without time zone),?)
|
||||
main.get_air_temperature_date(cast(to_timestamp(?, 'YYYYMMDD HH24') as timestamp without time zone),?),
|
||||
main.get_point_id(?,?,?)
|
||||
);
|
||||
""";
|
||||
String point_id=null;
|
||||
if(db_all) {
|
||||
point_id = DBTools.getPointId(st_all, country_id, lon, lat);
|
||||
if(point_id!=null) {
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setFloat(1, dataArrayTmp.getFloat(pos));
|
||||
pstmt.setLong(2, Long.valueOf(country_id));
|
||||
pstmt.setLong(3, Long.valueOf(point_id));
|
||||
pstmt.setString(4, date + " " + time);
|
||||
pstmt.setInt(5, Integer.valueOf(forecast));
|
||||
pstmt.setString(3, date + " " + time);
|
||||
pstmt.setInt(4, Integer.valueOf(forecast));
|
||||
pstmt.setLong(5, Long.valueOf(country_id));
|
||||
pstmt.setDouble(6, lon);
|
||||
pstmt.setDouble(7, lat);
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("E10:"+ex.getMessage(),ex);
|
||||
//throw new Exception("Failed insert ...");
|
||||
}
|
||||
throw new Exception("Failed insert ...");
|
||||
}
|
||||
}
|
||||
if(db_ru) {
|
||||
point_id = DBTools.getPointId(st_ru, country_id, lon, lat);
|
||||
if(point_id!=null) {
|
||||
try (PreparedStatement pstmt = conn_ru.prepareStatement(sql)) {
|
||||
pstmt.setFloat(1, dataArrayTmp.getFloat(pos));
|
||||
pstmt.setLong(2, Long.valueOf(country_id));
|
||||
pstmt.setLong(3, Long.valueOf(point_id));
|
||||
pstmt.setString(4, date + " " + time);
|
||||
pstmt.setInt(5, Integer.valueOf(forecast));
|
||||
pstmt.setString(3, date + " " + time);
|
||||
pstmt.setInt(4, Integer.valueOf(forecast));
|
||||
pstmt.setLong(5, Long.valueOf(country_id));
|
||||
pstmt.setDouble(6, lon);
|
||||
pstmt.setDouble(7, lat);
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("E11:"+ex.getMessage(),ex);
|
||||
//throw new Exception("Failed insert ...");
|
||||
}
|
||||
throw new Exception("Failed insert ...");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -371,14 +389,43 @@ public class AirTemperature implements ServletContextAware {
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.error(ex.getMessage(),ex);
|
||||
}
|
||||
|
||||
//Cut data piece from big country of Russia
|
||||
try {
|
||||
String sql="delete from main.points p where country_id=7 and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),ST_SetSRID(st_makepoint(p.lon,p.lat),4326));";
|
||||
if(st_all!=null) st_all.executeUpdate(sql);
|
||||
if(st_ru!=null) st_ru.executeUpdate(sql);
|
||||
//Deleting readings located in northern latitudes since locusts do not live there.
|
||||
{
|
||||
//String sql="delete from main.points p where country_id=7 and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),ST_SetSRID(st_makepoint(p.lon,p.lat),4326));";
|
||||
String sql= """
|
||||
delete from main.air_temperature where id in
|
||||
(
|
||||
select a.id from
|
||||
main.air_temperature a
|
||||
join main.points p on p.id=a.point_id
|
||||
where
|
||||
a.country_id=7
|
||||
and a.air_temperature_date_id = main.get_air_temperature_date(cast(to_timestamp(?, 'YYYYMMDD HH24') as timestamp without time zone),?)
|
||||
and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),ST_SetSRID(st_makepoint(p.lon,p.lat),4326))
|
||||
)
|
||||
""";
|
||||
if(conn_all!=null) {
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setString(1, date + " " + time);
|
||||
pstmt.setInt(2, Integer.valueOf(forecast));
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N11:"+ex.getMessage(),ex);
|
||||
logger.error("E10.1:"+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
if(conn_ru!=null) {
|
||||
try (PreparedStatement pstmt = conn_ru.prepareStatement(sql)) {
|
||||
pstmt.setString(1, date + " " + time);
|
||||
pstmt.setInt(2, Integer.valueOf(forecast));
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("E11:"+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@ -410,23 +457,7 @@ public class AirTemperature implements ServletContextAware {
|
||||
try { if(conn_ru!=null) conn_ru.close();} catch (SQLException ex) {logger.error("N15:"+ex.getMessage(),ex);}
|
||||
|
||||
result+="End!<br>";
|
||||
return result;
|
||||
}
|
||||
|
||||
//---------------------------------------------------------------------------
|
||||
public static String CutBeforeFirst(StringBuffer str,String ch)
|
||||
{
|
||||
int pos=str.indexOf(ch);
|
||||
String result="";
|
||||
if(pos==-1)
|
||||
{
|
||||
result.concat(str.toString());
|
||||
str.delete(0,str.length());
|
||||
}else
|
||||
{
|
||||
result=str.substring(0,pos);
|
||||
str.delete(0,pos+1);
|
||||
}
|
||||
System.out.println("Done download and save");
|
||||
return result;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
@ -441,7 +472,7 @@ public class AirTemperature implements ServletContextAware {
|
||||
|
||||
String result="";
|
||||
|
||||
Connection conn_all = getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_all = DBTools.getConn(db_url_all,db_login_all,db_password_all);
|
||||
|
||||
if(conn_all!=null)
|
||||
{
|
||||
@ -492,5 +523,91 @@ public class AirTemperature implements ServletContextAware {
|
||||
return result;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
@CrossOrigin
|
||||
@RequestMapping(value = "/geodatalist/getAirTemperature",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<Object> getAirTemperature(HttpServletResponse response, HttpServletRequest request, @RequestBody PointModel pointModel, @CookieValue(value = "lng", defaultValue = "1") String language_id) {
|
||||
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
|
||||
response.addHeader("Cache-Control", headerValue);
|
||||
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
float val = -999;
|
||||
|
||||
Connection conn_all = DBTools.getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_ru = DBTools.getConn(db_url_ru,db_login_ru,db_password_ru);
|
||||
|
||||
String sql;
|
||||
|
||||
if(pointModel.getDate()==null){
|
||||
//I assume that the dates in all databases are the same.
|
||||
sql = """
|
||||
select max(date) from main.air_temperature_dates where hours=?;
|
||||
""";
|
||||
if(conn_all!=null){
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setInt(1, pointModel.getHours());
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
pointModel.setDate(rs.getString(1));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sql = """
|
||||
select main.get_air_temperature(?::TIMESTAMP WITHOUT TIME ZONE,?,?,?) - 273.15
|
||||
""";
|
||||
if(conn_all!=null) {
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setString(1, pointModel.getDate());
|
||||
pstmt.setInt(2, pointModel.getHours());
|
||||
pstmt.setDouble(3, pointModel.getLon());
|
||||
pstmt.setDouble(4, pointModel.getLat());
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
val = rs.getFloat(1);
|
||||
if (rs.wasNull()) {
|
||||
val = -999;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
}
|
||||
}
|
||||
if(conn_ru!=null && val == -999) {
|
||||
try (PreparedStatement pstmt = conn_ru.prepareStatement(sql)) {
|
||||
pstmt.setString(1, pointModel.getDate());
|
||||
pstmt.setInt(2, pointModel.getHours());
|
||||
pstmt.setDouble(3, pointModel.getLon());
|
||||
pstmt.setDouble(4, pointModel.getLat());
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
val = rs.getFloat(1);
|
||||
if (rs.wasNull()) {
|
||||
val = -999;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
}
|
||||
}
|
||||
|
||||
result.put("error_code", 0);
|
||||
result.put("date", pointModel.getDate());
|
||||
if(val!=-999){
|
||||
result.put("value", val);
|
||||
}else{
|
||||
result.put("value", null);
|
||||
}
|
||||
return new ResponseEntity<>(result, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
30
src/main/java/org/ccalm/weather/BookController.java
Normal file
30
src/main/java/org/ccalm/weather/BookController.java
Normal file
@ -0,0 +1,30 @@
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.awt.print.Book;
|
||||
import java.util.Collection;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/book")
|
||||
public class BookController {
|
||||
|
||||
//@Autowired
|
||||
//private BookRepository repository;
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public String findById(@PathVariable long id) {
|
||||
return "";//repository.findById(id) .orElseThrow(() -> new BookNotFoundException());
|
||||
}
|
||||
|
||||
@GetMapping("/")
|
||||
public String findBooks() {
|
||||
return "";//repository.getBooks();
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public String updateBook(@PathVariable("id") final String id, @RequestBody final Book book) {
|
||||
return "";//book;
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,8 @@
|
||||
package org.ccalm.weather;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
@ -8,15 +11,111 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONException;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Controller
|
||||
public class MainController {
|
||||
|
||||
@Value("${spring.application.name}")
|
||||
String application_name = "";
|
||||
|
||||
@CrossOrigin
|
||||
@GetMapping("/")
|
||||
@RequestMapping(value = "/",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
|
||||
@ResponseBody
|
||||
public String getIndex(Model model) {
|
||||
return "The weather list is working! <br><a href=\"./geodatalist\">/geodatalist</a>";
|
||||
public ResponseEntity<String> getIndex(Model model) {
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json.put("error_code",0);
|
||||
json.put("error_message","");
|
||||
json.put("error_marker",(String)null);
|
||||
String buildDate="";
|
||||
//String buildVersion="";
|
||||
try {
|
||||
InputStream inputStream = MainController.class.getClassLoader().getResourceAsStream("META-INF/build-info.properties");
|
||||
if (inputStream != null) {
|
||||
Properties properties = new Properties();
|
||||
properties.load(inputStream);
|
||||
buildDate = properties.getProperty("build.time");
|
||||
//buildVersion = properties.getProperty("build.version");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
json.put("build_date",buildDate);
|
||||
//json.put("build_version",buildVersion);
|
||||
json.put("name",application_name);
|
||||
//json.put("active_connections",dataSource.getHikariPoolMXBean().getActiveConnections());
|
||||
//json.put("idle_connections",dataSource.getHikariPoolMXBean().getIdleConnections());
|
||||
|
||||
// Вывод всех зарегистрированных маршрутов в системе
|
||||
ApplicationContext context = SpringContext.getApplicationContext();
|
||||
if (context != null) {
|
||||
RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);
|
||||
Set<String> endpoints = mapping.getHandlerMethods().keySet().stream()
|
||||
.map(info -> info.toString())
|
||||
.collect(Collectors.toSet());
|
||||
System.out.println("=== Registered API endpoints ===");
|
||||
endpoints.forEach(System.out::println);
|
||||
}
|
||||
|
||||
} catch (JSONException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return ResponseEntity.ok(json.toString());
|
||||
|
||||
/*
|
||||
String buildDate="";
|
||||
//String buildVersion="";
|
||||
try {
|
||||
InputStream inputStream = MainController.class.getClassLoader().getResourceAsStream("META-INF/build-info.properties");
|
||||
if (inputStream != null) {
|
||||
Properties properties = new Properties();
|
||||
properties.load(inputStream);
|
||||
buildDate = properties.getProperty("build.time");
|
||||
//buildVersion = properties.getProperty("build.version");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
String result="buildDate = " + buildDate + "<br><br>";
|
||||
result+="""
|
||||
The weather list is working! <br><a href=\"./geodatalist\">/geodatalist</a>
|
||||
""";
|
||||
return result;
|
||||
*/
|
||||
}
|
||||
|
||||
@CrossOrigin
|
||||
@GetMapping("/geodatalist/")
|
||||
@ResponseBody
|
||||
public String getIndex2(Model model) {
|
||||
String buildDate="";
|
||||
//String buildVersion="";
|
||||
try {
|
||||
InputStream inputStream = MainController.class.getClassLoader().getResourceAsStream("META-INF/build-info.properties");
|
||||
if (inputStream != null) {
|
||||
Properties properties = new Properties();
|
||||
properties.load(inputStream);
|
||||
buildDate = properties.getProperty("build.time");
|
||||
//buildVersion = properties.getProperty("build.version");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
String result="buildDate = " + buildDate + "<br><br>";
|
||||
result+="""
|
||||
The weather list is working! <br><a href=\"./geodatalist\">/geodatalist</a>
|
||||
""";
|
||||
return result;
|
||||
}
|
||||
|
||||
@CrossOrigin
|
||||
@ -25,8 +124,8 @@ public class MainController {
|
||||
public String getGeoDataList(Model model) {
|
||||
return """
|
||||
<a href="/geodatalist/AirTemperatureDates">AirTemperatureDates</a><br><form action="/geodatalist/AirTemperature" method="get"><label for="fname">Date:</label><input type="text" name="date" value="20250107"><input type="submit" value="Submit"></form><br>
|
||||
<a href="/geodatalist/PrecipitationDates">PrecipitationDates</a><br><form action="/geodatalist/Precipitation" method="get"><label for="fname">Date:</label><input type="text" name="date" value=""20250107"><input type="submit" value="Submit"></form><br>
|
||||
<a href="/geodatalist/SoilDates">SoilDates</a><br><form action="/geodatalist/DownloadSoil" method="get"><label for="fname">Date:</label><input type="text" name="date" value=""20250107"><label for="forecast">Forecast:</label><input type="text" name="forecast" value="000"><input type="submit" value="Submit"></form><br>
|
||||
<a href="/geodatalist/PrecipitationDates">PrecipitationDates</a><br><form action="/geodatalist/Precipitation" method="get"><label for="fname">Date:</label><input type="text" name="date" value="20250107"><input type="submit" value="Submit"></form><br>
|
||||
<a href="/geodatalist/SoilDates">SoilDates</a><br><form action="/geodatalist/DownloadSoil" method="get"><label for="fname">Date:</label><input type="text" name="date" value="20250107"><label for="forecast">Forecast:</label><input type="text" name="forecast" value="000"><input type="submit" value="Submit"></form><br>
|
||||
""";
|
||||
}
|
||||
|
||||
|
||||
@ -4,43 +4,30 @@ import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.sql.*;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.ccalm.weather.models.PointModel;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import tctable.Tools;
|
||||
import tools.DBTools;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.context.ServletContextAware;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
//import main.DownloadFromHTTP;
|
||||
//import org.ccalm.weather.WeatherDownload;
|
||||
@ -73,13 +60,32 @@ public class Precipitation implements ServletContextAware {
|
||||
|
||||
private jakarta.servlet.ServletContext context;
|
||||
|
||||
//---------------------------------------------------------------------------
|
||||
public JSONObject createJSONError(int code, String message, String setting, String marker) {
|
||||
JSONObject json = new JSONObject();
|
||||
//try {
|
||||
json.put("error_code", code);
|
||||
if(message!=null && !message.isBlank()) {
|
||||
json.put("error_message", Arrays.asList(message));
|
||||
}
|
||||
if(setting!=null && !setting.isBlank()) {
|
||||
json.put("error_setting", Arrays.asList(setting));
|
||||
}
|
||||
if(marker!=null && !marker.isBlank()) {
|
||||
json.put("error_marker", marker);
|
||||
}
|
||||
//} catch (JSONException e) {
|
||||
// logger.error(e);
|
||||
//}
|
||||
return json;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
@Override
|
||||
public void setServletContext(jakarta.servlet.ServletContext servletContext) {
|
||||
this.context=servletContext;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
public static String CutBeforeFirst(StringBuffer str,String ch)
|
||||
/*public static String CutBeforeFirst(StringBuffer str,String ch)
|
||||
{
|
||||
int pos=str.indexOf(ch);
|
||||
String result="";
|
||||
@ -93,25 +99,13 @@ public class Precipitation implements ServletContextAware {
|
||||
str.delete(0,pos+1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
public Connection getConn(String url, String login,String password){
|
||||
Connection conn = null;
|
||||
try{
|
||||
Class.forName("org.postgresql.Driver");
|
||||
conn = DriverManager.getConnection(url,login,password);
|
||||
}catch(Exception ex)
|
||||
{
|
||||
logger.error("N1: "+ex.getMessage()+"<br>",ex);
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
}*/
|
||||
//---------------------------------------------------------------------------
|
||||
/**
|
||||
* Example http://127.0.0.1:8080/AirTemperature
|
||||
* Example https://127.0.0.1:8081/geodatalist/Precipitation or https://127.0.0.1:8081/geodatalist/Precipitation?date=20250531
|
||||
* @param response
|
||||
* @param date
|
||||
* @return
|
||||
* @return HTML string
|
||||
*/
|
||||
@RequestMapping(value = "/geodatalist/Precipitation",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
|
||||
@ResponseBody
|
||||
@ -129,10 +123,32 @@ public class Precipitation implements ServletContextAware {
|
||||
if (!dir.exists()) dir.mkdirs();
|
||||
|
||||
//response.getWriter().append("Served at: ").append(request.getContextPath());
|
||||
Connection conn_all = getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_ru = getConn(db_url_ru,db_login_ru,db_password_ru);
|
||||
|
||||
//Example request: http://localhost:8080/Precipitation?date=20210531
|
||||
Connection conn_all = DBTools.getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_ru = DBTools.getConn(db_url_ru,db_login_ru,db_password_ru);
|
||||
Statement st_all=null;
|
||||
Statement st_ru=null;
|
||||
try {
|
||||
st_all = conn_all.createStatement();
|
||||
st_ru = conn_ru.createStatement();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N3:"+ex.getMessage(),ex);
|
||||
}
|
||||
if(date==null || date.equals(""))
|
||||
{
|
||||
//Если день не задан то ищем максимальный день не старше 10 дней и прибавляем 1 день
|
||||
String sql="select to_char(max(date)+'1 days'::interval, 'YYYYMMDD') from main.precipitation_dates where hours=0 and date > now() - '10 days'::interval";
|
||||
if(st_all!=null) {
|
||||
try {
|
||||
try (ResultSet rs = st_all.executeQuery(sql)) {
|
||||
if (rs.next()) {
|
||||
date = rs.getString(1);
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N4:"+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(date==null || date.equals(""))
|
||||
{
|
||||
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
|
||||
@ -145,12 +161,18 @@ public class Precipitation implements ServletContextAware {
|
||||
//Build URL to download
|
||||
String URL = "https://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/gfs."+date+"/"+time+"/atmos/gfs.t"+time+"z.pgrb2.0p25.f"+forecast;
|
||||
|
||||
File f = new File(data_dir+"temp"+File.separator+"pre_text.idx");
|
||||
if(f.exists()) {
|
||||
if (!f.delete()) {
|
||||
File f1 = new File(data_dir+"temp"+File.separator+"pre_text.idx");
|
||||
if(f1.exists()) {
|
||||
if (!f1.delete()) {
|
||||
System.out.println("Failed to delete the file \"pre_text.idx\".");
|
||||
}
|
||||
}
|
||||
File f2 = new File(data_dir+"temp"+File.separator+"pre_text.idx");
|
||||
if(f2.exists()) {
|
||||
if (!f2.delete()) {
|
||||
System.out.println("Failed to delete the file \"pre_text.f000\".");
|
||||
}
|
||||
}
|
||||
|
||||
WeatherDownload wd = new WeatherDownload();
|
||||
if(wd.download(URL+".idx", data_dir+"temp"+File.separator+"pre_text.idx", "0", ""))
|
||||
@ -181,12 +203,12 @@ public class Precipitation implements ServletContextAware {
|
||||
if(!strPos1.isEmpty())
|
||||
{
|
||||
StringBuffer answer1=new StringBuffer(strPos1);
|
||||
CutBeforeFirst(answer1,":");
|
||||
String posStart = CutBeforeFirst(answer1,":");
|
||||
Tools.CutBeforeFirst(answer1,":");
|
||||
String posStart = Tools.CutBeforeFirst(answer1,":");
|
||||
|
||||
StringBuffer answer2=new StringBuffer(strPos2);
|
||||
CutBeforeFirst(answer2,":");
|
||||
String posEnd = CutBeforeFirst(answer2,":");
|
||||
Tools.CutBeforeFirst(answer2,":");
|
||||
String posEnd = Tools.CutBeforeFirst(answer2,":");
|
||||
if(posEnd==null || posEnd.equals("")) posEnd=""; else
|
||||
{
|
||||
posEnd=String.valueOf(Long.parseLong(posEnd)-1);
|
||||
@ -253,14 +275,6 @@ public class Precipitation implements ServletContextAware {
|
||||
}
|
||||
dimIt = null;
|
||||
|
||||
Statement st_all=null;
|
||||
Statement st_ru=null;
|
||||
try {
|
||||
st_all = conn_all.createStatement();
|
||||
st_ru = conn_ru.createStatement();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N3:"+ex.getMessage(),ex);
|
||||
}
|
||||
|
||||
try {
|
||||
st_all.executeUpdate("BEGIN TRANSACTION;");
|
||||
@ -288,16 +302,16 @@ public class Precipitation implements ServletContextAware {
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N7:"+ex.getMessage(),ex);
|
||||
}
|
||||
if(Integer.parseInt(forecast)!=0) {
|
||||
logger.info("Delete all old forecasts");
|
||||
try {
|
||||
String sql="delete from main.precipitation_dates where hours="+forecast;
|
||||
st_all.executeUpdate(sql);
|
||||
st_ru.executeUpdate(sql);
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N8: "+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
// if(Integer.parseInt(forecast)!=0) {
|
||||
// logger.info("Delete all old forecasts");
|
||||
// try {
|
||||
// String sql="delete from main.precipitation_dates where hours="+forecast; у меня всё 24 часа вот и всё и удалит..... не раскоментировать!
|
||||
// st_all.executeUpdate(sql);
|
||||
// st_ru.executeUpdate(sql);
|
||||
// } catch (SQLException ex) {
|
||||
// logger.error("N8: "+ex.getMessage(),ex);
|
||||
// }
|
||||
// }
|
||||
try {
|
||||
st_all.executeUpdate("END TRANSACTION;");
|
||||
st_ru.executeUpdate("END TRANSACTION;");
|
||||
@ -312,6 +326,7 @@ public class Precipitation implements ServletContextAware {
|
||||
}
|
||||
|
||||
int pos=0;
|
||||
try{
|
||||
for(int nLat=0;nLat<dataArrayLat.getSize();nLat++)
|
||||
{
|
||||
for(int nLon=0;nLon<dataArrayLon.getSize();nLon++)
|
||||
@ -337,52 +352,49 @@ public class Precipitation implements ServletContextAware {
|
||||
if(!country_id.isEmpty()) db_ru=true;
|
||||
}
|
||||
|
||||
if(country_id!=null && !country_id.equals("") && !country_id.equals("null"))
|
||||
if(country_id!=null && !country_id.isEmpty() && !country_id.equals("null"))
|
||||
{
|
||||
String sql= """
|
||||
insert into main.precipitation(
|
||||
val,
|
||||
country_id,
|
||||
point_id,
|
||||
air_temperature_date_id
|
||||
precipitation_date_id,
|
||||
point_id
|
||||
)values(
|
||||
?,
|
||||
?,
|
||||
?,
|
||||
main.get_precipitation_date(cast(to_timestamp(?, 'YYYYMMDD HH24') as timestamp without time zone),?)
|
||||
main.get_precipitation_date(cast(to_timestamp(?, 'YYYYMMDD HH24') as timestamp without time zone),?),
|
||||
main.get_point_id(?,?,?)
|
||||
);
|
||||
""";
|
||||
String point_id=null;
|
||||
if(db_all) {
|
||||
point_id = DBTools.getPointId(st_all, country_id, lon, lat);
|
||||
if(point_id!=null) {
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setFloat(1, dataArrayTmp.getFloat(pos));
|
||||
pstmt.setLong(2, Long.valueOf(country_id));
|
||||
pstmt.setLong(3, Long.valueOf(point_id));
|
||||
pstmt.setString(4, date + " " + time);
|
||||
pstmt.setInt(5, Integer.valueOf(forecast));
|
||||
pstmt.setString(3, date + " " + time);
|
||||
pstmt.setInt(4, Integer.valueOf(forecast));
|
||||
pstmt.setLong(5, Long.valueOf(country_id));
|
||||
pstmt.setDouble(6, lon);
|
||||
pstmt.setDouble(7, lat);
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("E10:"+ex.getMessage(),ex);
|
||||
//throw new Exception("Failed insert precipitation...");
|
||||
}
|
||||
throw new Exception("Failed insert precipitation...");
|
||||
}
|
||||
}
|
||||
if(db_ru) {
|
||||
point_id = DBTools.getPointId(st_ru, country_id, lon, lat);
|
||||
if(point_id!=null) {
|
||||
try (PreparedStatement pstmt = conn_ru.prepareStatement(sql)) {
|
||||
pstmt.setFloat(1, dataArrayTmp.getFloat(pos));
|
||||
pstmt.setLong(2, Long.valueOf(country_id));
|
||||
pstmt.setLong(3, Long.valueOf(point_id));
|
||||
pstmt.setString(4, date + " " + time);
|
||||
pstmt.setInt(5, Integer.valueOf(forecast));
|
||||
pstmt.setString(3, date + " " + time);
|
||||
pstmt.setInt(4, Integer.valueOf(forecast));
|
||||
pstmt.setLong(5, Long.valueOf(country_id));
|
||||
pstmt.setDouble(6, lon);
|
||||
pstmt.setDouble(7, lat);
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("E10:"+ex.getMessage(),ex);
|
||||
//throw new Exception("Failed insert precipitation...");
|
||||
}
|
||||
throw new Exception("Failed insert precipitation...");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -392,14 +404,42 @@ public class Precipitation implements ServletContextAware {
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
|
||||
//Cut data piece from big country of Russia
|
||||
try {
|
||||
String sql="delete from main.points p where country_id=7 and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),ST_SetSRID(st_makepoint(p.lon,p.lat),4326));";
|
||||
st_all.executeUpdate(sql);
|
||||
st_ru.executeUpdate(sql);
|
||||
} catch (Exception ex) {
|
||||
logger.error(ex.getMessage(),ex);
|
||||
}
|
||||
//Deleting readings located in northern latitudes since locusts do not live there.
|
||||
{
|
||||
//String sql="delete from main.points p where country_id=7 and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),ST_SetSRID(st_makepoint(p.lon,p.lat),4326));";
|
||||
String sql= """
|
||||
delete from main.precipitation where id in
|
||||
(
|
||||
select a.id from
|
||||
main.precipitation a
|
||||
join main.points p on p.id=a.point_id
|
||||
where
|
||||
a.country_id=7
|
||||
and a.precipitation_date_id = main.get_precipitation_date(cast(to_timestamp(?, 'YYYYMMDD HH24') as timestamp without time zone),?)
|
||||
and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),ST_SetSRID(st_makepoint(p.lon,p.lat),4326))
|
||||
)
|
||||
""";
|
||||
if(conn_all!=null) {
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setString(1, date + " " + time);
|
||||
pstmt.setInt(2, Integer.valueOf(forecast));
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N11:"+ex.getMessage(),ex);
|
||||
logger.error("E10.1:"+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
if(conn_ru!=null) {
|
||||
try (PreparedStatement pstmt = conn_ru.prepareStatement(sql)) {
|
||||
pstmt.setString(1, date + " " + time);
|
||||
pstmt.setInt(2, Integer.valueOf(forecast));
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("E11:"+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@ -443,7 +483,7 @@ public class Precipitation implements ServletContextAware {
|
||||
String result="";
|
||||
|
||||
//Load DB configuration from "config.xml"
|
||||
Connection conn_all = getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_all = DBTools.getConn(db_url_all,db_login_all,db_password_all);
|
||||
|
||||
if(conn_all!=null)
|
||||
{
|
||||
@ -495,5 +535,91 @@ public class Precipitation implements ServletContextAware {
|
||||
return result;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
//Weighted interpolation
|
||||
@RequestMapping(value = "/geodatalist/getPrecipitation",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<Object> getPrecipitation(HttpServletResponse response, HttpServletRequest request, @RequestBody PointModel pointModel, @CookieValue(value = "lng", defaultValue = "1") String language_id) {
|
||||
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
|
||||
response.addHeader("Cache-Control", headerValue);
|
||||
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
Connection conn_all = DBTools.getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_ru = DBTools.getConn(db_url_ru,db_login_ru,db_password_ru);
|
||||
float val=-999;
|
||||
|
||||
String sql;
|
||||
|
||||
if(pointModel.getDate()==null){
|
||||
//I assume that the dates in all databases are the same.
|
||||
sql = """
|
||||
select max(date) from main.precipitation_dates where hours=?;
|
||||
""";
|
||||
if(conn_all!=null){
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setInt(1, pointModel.getHours());
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
pointModel.setDate(rs.getString(1));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sql="""
|
||||
select main.get_precipitation(?::TIMESTAMP WITHOUT TIME ZONE,?,?,?) - 273.15
|
||||
""";
|
||||
if(conn_all!=null) {
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setString(1, pointModel.getDate());
|
||||
pstmt.setInt(2, pointModel.getHours());
|
||||
pstmt.setDouble(3, pointModel.getLon());
|
||||
pstmt.setDouble(4, pointModel.getLat());
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
val = rs.getFloat(1);
|
||||
if (rs.wasNull()) {
|
||||
val = -999;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
}
|
||||
}
|
||||
if(conn_ru!=null && val == -999) {
|
||||
try (PreparedStatement pstmt = conn_ru.prepareStatement(sql)) {
|
||||
pstmt.setString(1, pointModel.getDate());
|
||||
pstmt.setInt(2, pointModel.getHours());
|
||||
pstmt.setDouble(3, pointModel.getLon());
|
||||
pstmt.setDouble(4, pointModel.getLat());
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
val = rs.getFloat(1);
|
||||
if (rs.wasNull()) {
|
||||
val = -999;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
}
|
||||
}
|
||||
|
||||
result.put("error_code", 0);
|
||||
result.put("date", pointModel.getDate());
|
||||
if(val!=-999){
|
||||
result.put("value", val);
|
||||
}else{
|
||||
result.put("value", null);
|
||||
}
|
||||
return new ResponseEntity<>(result, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,46 +4,32 @@ import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Type;
|
||||
import java.sql.*;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.ccalm.weather.models.PointModel;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import tools.DBTools;
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.context.ServletContextAware;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
//import main.DownloadFromHTTP;
|
||||
import org.ccalm.weather.WeatherDownload;
|
||||
import tctable.Tools;
|
||||
import ucar.ma2.Array;
|
||||
import ucar.nc2.Dimension;
|
||||
import ucar.nc2.Variable;
|
||||
@ -73,25 +59,32 @@ public class SoilTmperature implements ServletContextAware {
|
||||
|
||||
private ServletContext context;
|
||||
|
||||
//---------------------------------------------------------------------------
|
||||
public JSONObject createJSONError(int code, String message, String setting, String marker) {
|
||||
JSONObject json = new JSONObject();
|
||||
//try {
|
||||
json.put("error_code", code);
|
||||
if(message!=null && !message.isBlank()) {
|
||||
json.put("error_message", Arrays.asList(message));
|
||||
}
|
||||
if(setting!=null && !setting.isBlank()) {
|
||||
json.put("error_setting", Arrays.asList(setting));
|
||||
}
|
||||
if(marker!=null && !marker.isBlank()) {
|
||||
json.put("error_marker", marker);
|
||||
}
|
||||
//} catch (JSONException e) {
|
||||
// logger.error(e);
|
||||
//}
|
||||
return json;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
@Override
|
||||
public void setServletContext(jakarta.servlet.ServletContext servletContext) {
|
||||
this.context=context;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
public Connection getConn(String url, String login,String password){
|
||||
Connection conn = null;
|
||||
try{
|
||||
Class.forName("org.postgresql.Driver");
|
||||
conn = DriverManager.getConnection(url,login,password);
|
||||
}catch(Exception ex)
|
||||
{
|
||||
logger.error("N1: "+ex.getMessage()+"<br>",ex);
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
public static String CutBeforeFirst(StringBuffer str,String ch)
|
||||
/*public static String CutBeforeFirst(StringBuffer str,String ch)
|
||||
{
|
||||
int pos=str.indexOf(ch);
|
||||
String result="";
|
||||
@ -105,14 +98,14 @@ public class SoilTmperature implements ServletContextAware {
|
||||
str.delete(0,pos+1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}*/
|
||||
//---------------------------------------------------------------------------
|
||||
/**
|
||||
* Example: http://127.0.0.1:8081/geodatalist/DownloadSoil?forecast=000
|
||||
* @param response
|
||||
* @param forecast
|
||||
* @param date
|
||||
* @return
|
||||
* @return HTML string
|
||||
*/
|
||||
@RequestMapping(value = "/geodatalist/DownloadSoil",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
|
||||
@ResponseBody
|
||||
@ -133,13 +126,32 @@ public class SoilTmperature implements ServletContextAware {
|
||||
if (!dir.exists()) dir.mkdirs();
|
||||
|
||||
//response.getWriter().append("Served at: ").append(request.getContextPath());
|
||||
Connection conn_all = getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_ru = getConn(db_url_ru,db_login_ru,db_password_ru);
|
||||
|
||||
|
||||
//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
|
||||
Connection conn_all = DBTools.getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_ru = DBTools.getConn(db_url_ru,db_login_ru,db_password_ru);
|
||||
Statement st_all=null;
|
||||
Statement st_ru=null;
|
||||
try {
|
||||
st_all = conn_all.createStatement();
|
||||
st_ru = conn_ru.createStatement();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N3:"+ex.getMessage(),ex);
|
||||
}
|
||||
if(date==null || date.equals(""))
|
||||
{
|
||||
//Если день не задан то ищем максимальный день не старше 10 дней и прибавляем 1 день
|
||||
String sql="select to_char(max(date)+'1 days'::interval, 'YYYYMMDD') from main.soil_temperature_dates where hours=0 and date > now() - '10 days'::interval";
|
||||
if(st_all!=null) {
|
||||
try {
|
||||
try (ResultSet rs = st_all.executeQuery(sql)) {
|
||||
if (rs.next()) {
|
||||
date = rs.getString(1);
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N4:"+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(date==null || date.equals(""))
|
||||
{
|
||||
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
|
||||
@ -155,12 +167,18 @@ public class SoilTmperature implements ServletContextAware {
|
||||
//Build URL to download
|
||||
String URL = "https://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/gfs."+date+"/"+time+"/atmos/gfs.t"+time+"z.pgrb2.0p25.f"+forecast;
|
||||
|
||||
File f = new File(data_dir+"temp"+File.separator+"text.idx");
|
||||
if(f.exists()) {
|
||||
if (!f.delete()) {
|
||||
File f1 = new File(data_dir+"temp"+File.separator+"text.idx");
|
||||
if(f1.exists()) {
|
||||
if (!f1.delete()) {
|
||||
System.out.println("Failed to delete the file \"text.idx\".");
|
||||
}
|
||||
}
|
||||
File f2 = new File(data_dir+"temp"+File.separator+"text.f000");
|
||||
if(f2.exists()) {
|
||||
if (!f2.delete()) {
|
||||
System.out.println("Failed to delete the file \"text.f000\".");
|
||||
}
|
||||
}
|
||||
|
||||
WeatherDownload wd = new WeatherDownload();
|
||||
if(wd.download(URL+".idx", data_dir+"temp"+File.separator+"text.idx", "0", ""))
|
||||
@ -192,12 +210,12 @@ public class SoilTmperature implements ServletContextAware {
|
||||
{
|
||||
//String strPos1 = "250:146339365:d=2017022818:TSOIL:0-0.1 m below ground:anl:"
|
||||
StringBuffer answer1=new StringBuffer(strPos1);
|
||||
CutBeforeFirst(answer1,":");
|
||||
String posStart = CutBeforeFirst(answer1,":");
|
||||
Tools.CutBeforeFirst(answer1,":");
|
||||
String posStart = Tools.CutBeforeFirst(answer1,":");
|
||||
|
||||
StringBuffer answer2=new StringBuffer(strPos2);
|
||||
CutBeforeFirst(answer2,":");
|
||||
String posEnd = CutBeforeFirst(answer2,":");
|
||||
Tools.CutBeforeFirst(answer2,":");
|
||||
String posEnd = Tools.CutBeforeFirst(answer2,":");
|
||||
if(posEnd==null || posEnd.equals("")) posEnd=""; else
|
||||
{
|
||||
posEnd=String.valueOf(Long.parseLong(posEnd)-1);
|
||||
@ -271,15 +289,6 @@ public class SoilTmperature implements ServletContextAware {
|
||||
}
|
||||
dimIt = null;
|
||||
|
||||
Statement st_all=null;
|
||||
Statement st_ru=null;
|
||||
try {
|
||||
st_all = conn_all.createStatement();
|
||||
st_ru = conn_all.createStatement();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N3: "+ex.getMessage(),ex);
|
||||
}
|
||||
|
||||
try {
|
||||
st_all.executeUpdate("BEGIN TRANSACTION;");
|
||||
st_ru.executeUpdate("BEGIN TRANSACTION;");
|
||||
@ -331,6 +340,7 @@ public class SoilTmperature implements ServletContextAware {
|
||||
}
|
||||
|
||||
int pos=0;
|
||||
try{
|
||||
for(int nLat=0;nLat<dataArrayLat.getSize();nLat++)
|
||||
{
|
||||
for(int nLon=0;nLon<dataArrayLon.getSize();nLon++)
|
||||
@ -356,70 +366,94 @@ public class SoilTmperature implements ServletContextAware {
|
||||
if(!country_id.isEmpty()) db_ru=true;
|
||||
}
|
||||
|
||||
if(!country_id.isEmpty() && !country_id.equals("null"))
|
||||
if(country_id!=null && !country_id.isEmpty() && !country_id.equals("null"))
|
||||
{
|
||||
|
||||
String sql="""
|
||||
insert into main.soil_temperature(
|
||||
val,
|
||||
country_id,
|
||||
point_id,
|
||||
soil_temperature_date_id
|
||||
soil_temperature_date_id,
|
||||
point_id
|
||||
)values(
|
||||
?,
|
||||
?,
|
||||
?,
|
||||
main.get_soil_temperature_date(cast(to_timestamp(?, 'YYYYMMDD HH24') as timestamp without time zone),?)
|
||||
main.get_soil_temperature_date(cast(to_timestamp(?, 'YYYYMMDD HH24') as timestamp without time zone),?),
|
||||
main.get_point_id(?,?,?)
|
||||
);
|
||||
""";
|
||||
String point_id=null;
|
||||
if(db_all) {
|
||||
point_id = DBTools.getPointId(st_all, country_id, lon, lat);
|
||||
if(point_id!=null) {
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setFloat(1, dataArrayTmp.getFloat(pos));
|
||||
pstmt.setLong(2, Long.valueOf(country_id));
|
||||
pstmt.setLong(3, Long.valueOf(point_id));
|
||||
pstmt.setString(4, date + " " + time);
|
||||
pstmt.setInt(5, Integer.valueOf(forecast));
|
||||
pstmt.setString(3, date + " " + time);
|
||||
pstmt.setInt(4, Integer.valueOf(forecast));
|
||||
pstmt.setLong(5, Long.valueOf(country_id));
|
||||
pstmt.setDouble(6, lon);
|
||||
pstmt.setDouble(7, lat);
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("E10:"+ex.getMessage(),ex);
|
||||
//throw new Exception("Failed insert soil temperature...");
|
||||
}
|
||||
throw new Exception("Failed insert soil temperature...");
|
||||
}
|
||||
}
|
||||
if(db_ru) {
|
||||
point_id = DBTools.getPointId(st_ru, country_id, lon, lat);
|
||||
if(point_id!=null) {
|
||||
try (PreparedStatement pstmt = conn_ru.prepareStatement(sql)) {
|
||||
pstmt.setFloat(1, dataArrayTmp.getFloat(pos));
|
||||
pstmt.setLong(2, Long.valueOf(country_id));
|
||||
pstmt.setLong(3, Long.valueOf(point_id));
|
||||
pstmt.setString(4, date + " " + time);
|
||||
pstmt.setInt(5, Integer.valueOf(forecast));
|
||||
pstmt.setString(3, date + " " + time);
|
||||
pstmt.setInt(4, Integer.valueOf(forecast));
|
||||
pstmt.setLong(5, Long.valueOf(country_id));
|
||||
pstmt.setDouble(6, lon);
|
||||
pstmt.setDouble(7, lat);
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("E10:"+ex.getMessage(),ex);
|
||||
//throw new Exception("Failed insert soil temperature...");
|
||||
throw new Exception("Failed insert soil temperature...");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.error(ex.getMessage(),ex);
|
||||
}
|
||||
|
||||
//Cut data piece from big country of Russia
|
||||
try {
|
||||
String sql="delete from main.points p where country_id=7 and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),ST_SetSRID(st_makepoint(p.lon,p.lat),4326));";
|
||||
st_all.executeUpdate(sql);
|
||||
st_ru.executeUpdate(sql);
|
||||
//Deleting readings located in northern latitudes since locusts do not live there.
|
||||
{
|
||||
//String sql="delete from main.points p where country_id=7 and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),ST_SetSRID(st_makepoint(p.lon,p.lat),4326));";
|
||||
String sql= """
|
||||
delete from main.soil_temperature where id in
|
||||
(
|
||||
select a.id from
|
||||
main.soil_temperature a
|
||||
join main.points p on p.id=a.point_id
|
||||
where
|
||||
a.country_id=7
|
||||
and a.soil_temperature_date_id = main.get_soil_temperature_date(cast(to_timestamp(?, 'YYYYMMDD HH24') as timestamp without time zone),?)
|
||||
and not ST_Contains(ST_SetSRID(ST_GeomFromText('POLYGON((10.00 66.00,10.00 40.00,179.00 40.00,179.00 66.00,10.00 66.00))'),4326),ST_SetSRID(st_makepoint(p.lon,p.lat),4326))
|
||||
)
|
||||
""";
|
||||
if(conn_all!=null) {
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setString(1, date + " " + time);
|
||||
pstmt.setInt(2, Integer.valueOf(forecast));
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("N12: "+ex.getMessage(),ex);
|
||||
logger.error("E10.1:"+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
if(conn_ru!=null) {
|
||||
try (PreparedStatement pstmt = conn_ru.prepareStatement(sql)) {
|
||||
pstmt.setString(1, date + " " + time);
|
||||
pstmt.setInt(2, Integer.valueOf(forecast));
|
||||
pstmt.executeUpdate();
|
||||
} catch (SQLException ex) {
|
||||
logger.error("E11:"+ex.getMessage(),ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@ -462,7 +496,7 @@ public class SoilTmperature implements ServletContextAware {
|
||||
|
||||
String result="";
|
||||
|
||||
Connection conn_all = getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_all = DBTools.getConn(db_url_all,db_login_all,db_password_all);
|
||||
|
||||
if(conn_all!=null)
|
||||
{
|
||||
@ -515,5 +549,91 @@ public class SoilTmperature implements ServletContextAware {
|
||||
return result;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
//Weighted interpolation
|
||||
@RequestMapping(value = "/geodatalist/getSoil",method = {RequestMethod.POST,RequestMethod.GET},produces = "application/json;charset=utf-8")
|
||||
@ResponseBody
|
||||
public ResponseEntity<Object> getSoil(HttpServletResponse response, HttpServletRequest request, @RequestBody PointModel pointModel, @CookieValue(value = "lng", defaultValue = "1") String language_id) {
|
||||
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
|
||||
response.addHeader("Cache-Control", headerValue);
|
||||
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
Connection conn_all = DBTools.getConn(db_url_all,db_login_all,db_password_all);
|
||||
Connection conn_ru = DBTools.getConn(db_url_ru,db_login_ru,db_password_ru);
|
||||
float val=-999;
|
||||
|
||||
String sql;
|
||||
|
||||
if(pointModel.getDate()==null){
|
||||
//I assume that the dates in all databases are the same.
|
||||
sql = """
|
||||
select max(date) from main.soil_temperature_dates where hours=?;
|
||||
""";
|
||||
if(conn_all!=null){
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setInt(1, pointModel.getHours());
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
pointModel.setDate(rs.getString(1));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sql="""
|
||||
select main.get_soil_temperature(?::TIMESTAMP WITHOUT TIME ZONE,?,?,?) - 273.15
|
||||
""";
|
||||
if(conn_all!=null) {
|
||||
try (PreparedStatement pstmt = conn_all.prepareStatement(sql)) {
|
||||
pstmt.setString(1, pointModel.getDate());
|
||||
pstmt.setInt(2, pointModel.getHours());
|
||||
pstmt.setDouble(3, pointModel.getLon());
|
||||
pstmt.setDouble(4, pointModel.getLat());
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
val = rs.getFloat(1);
|
||||
if (rs.wasNull()) {
|
||||
val = -999;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
}
|
||||
}
|
||||
if(conn_ru!=null && val == -999) {
|
||||
try (PreparedStatement pstmt = conn_ru.prepareStatement(sql)) {
|
||||
pstmt.setString(1, pointModel.getDate());
|
||||
pstmt.setInt(2, pointModel.getHours());
|
||||
pstmt.setDouble(3, pointModel.getLon());
|
||||
pstmt.setDouble(4, pointModel.getLat());
|
||||
try (ResultSet rs = pstmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
val = rs.getFloat(1);
|
||||
if (rs.wasNull()) {
|
||||
val = -999;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
logger.error(uuid,e);
|
||||
}
|
||||
}
|
||||
|
||||
result.put("error_code", 0);
|
||||
result.put("date", pointModel.getDate());
|
||||
if(val!=-999){
|
||||
result.put("value", val);
|
||||
}else{
|
||||
result.put("value", null);
|
||||
}
|
||||
return new ResponseEntity<>(result, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
|
||||
19
src/main/java/org/ccalm/weather/SpringContext.java
Normal file
19
src/main/java/org/ccalm/weather/SpringContext.java
Normal file
@ -0,0 +1,19 @@
|
||||
package org.ccalm.weather;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SpringContext implements ApplicationContextAware {
|
||||
private static ApplicationContext context;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) {
|
||||
context = applicationContext;
|
||||
}
|
||||
|
||||
public static ApplicationContext getApplicationContext() {
|
||||
return context;
|
||||
}
|
||||
}
|
||||
54
src/main/java/org/ccalm/weather/Translation.java
Normal file
54
src/main/java/org/ccalm/weather/Translation.java
Normal file
@ -0,0 +1,54 @@
|
||||
package org.ccalm.weather;
|
||||
|
||||
//import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
|
||||
public class Translation {
|
||||
/*public int language_id;
|
||||
public NamedParameterJdbcTemplate jdbcTemplate;
|
||||
Translation(String lng, NamedParameterJdbcTemplate jdbcTemplate){
|
||||
language_id=1;
|
||||
switch (lng) {
|
||||
case "kz":
|
||||
case "kk":
|
||||
language_id = 2;
|
||||
break;
|
||||
case "en":
|
||||
language_id = 3;
|
||||
break;
|
||||
case "uz":
|
||||
language_id = 4;
|
||||
break;
|
||||
case "ru":
|
||||
default:
|
||||
language_id = 1;
|
||||
break;
|
||||
}
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}*/
|
||||
|
||||
String trt(String text){
|
||||
/*String sql = """
|
||||
select
|
||||
translation
|
||||
from
|
||||
main._translations
|
||||
where
|
||||
del=false
|
||||
and language_id=:language_id
|
||||
and identifier=:identifier;
|
||||
""";
|
||||
MapSqlParameterSource parameters = new MapSqlParameterSource();
|
||||
parameters.addValue("language_id", language_id);
|
||||
parameters.addValue("identifier", text);
|
||||
List<String> ret = jdbcTemplate.query(sql, parameters, new DBTools.JsonRowMapper());
|
||||
int i = 0;
|
||||
for (i = 0; i < ret.size(); i++) {
|
||||
JSONObject json = new JSONObject(ret.get(i));
|
||||
text = json.getString("translation");
|
||||
}
|
||||
if(i==0){
|
||||
text = text.replace("_", " ");
|
||||
}*/
|
||||
return text;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,96 @@
|
||||
package org.ccalm.weather.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Schema(
|
||||
description = "Error API response",
|
||||
example = "{ \"error_code\": 10000, \"error_message\": [\"Internal_Server_Error\",\"Please_log_in\"], \"error_setting\": [\"99;day\",\"1;2\"], \"error_marker\": \"2a449883-c7c6-468e-b3ae-5f73fc96627d\" }"
|
||||
)
|
||||
|
||||
public class ErrorResponseModel {
|
||||
|
||||
@Schema(description = "Error code", example = "10000")
|
||||
@JsonProperty("error_code")
|
||||
private int errorCode;
|
||||
|
||||
@Schema(description = "List of error descriptions", example = "[\"Internal_Server_Error\",\"Please_log_in\"]")
|
||||
@JsonProperty("error_message")
|
||||
private List<String> errorMessage;
|
||||
|
||||
@Schema(description = "Options for translated text", example = "[\"99;day\",\"1;2\"]")
|
||||
@JsonProperty("error_setting")
|
||||
private List<String> errorSetting;
|
||||
|
||||
@Schema(description = "Unique identifier for searching in the database", example = "4260aad8-f7ee-4be4-b52c-15d56ec83232")
|
||||
@JsonProperty("error_marker")
|
||||
private String errorMarker;
|
||||
|
||||
public ErrorResponseModel(int errorCode) {
|
||||
this.errorCode = errorCode;
|
||||
this.errorMessage = null;
|
||||
this.errorSetting = null;
|
||||
this.errorMarker = null;
|
||||
}
|
||||
|
||||
public ErrorResponseModel(int errorCode, List<String> errorMessage, String errorMarker) {
|
||||
this.errorCode = errorCode;
|
||||
this.errorMessage = errorMessage;
|
||||
this.errorMarker = errorMarker;
|
||||
}
|
||||
|
||||
public ErrorResponseModel(int errorCode, String errorMessage, String errorMarker) {
|
||||
this.errorCode = errorCode;
|
||||
this.errorMessage = Collections.singletonList(errorMessage);
|
||||
this.errorMarker = errorMarker;
|
||||
}
|
||||
|
||||
public ErrorResponseModel(int errorCode, String errorMessage, String errorSetting, String errorMarker) {
|
||||
this.errorCode = errorCode;
|
||||
this.errorMessage = Collections.singletonList(errorMessage);
|
||||
this.errorSetting = Collections.singletonList(errorSetting);
|
||||
this.errorMarker = errorMarker;
|
||||
}
|
||||
|
||||
public ErrorResponseModel(int errorCode, List<String> errorMessage, List<String> errorSetting, String errorMarker) {
|
||||
this.errorCode = errorCode;
|
||||
this.errorMessage = errorMessage;
|
||||
this.errorSetting = errorSetting;
|
||||
this.errorMarker = errorMarker;
|
||||
}
|
||||
|
||||
public int getError_code() {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
public void setError_code(int errorCode) {
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public List<String> getError_message() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setError_message(List<String> errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public void setError_setting(List<String> errorSetting) {
|
||||
this.errorSetting = errorSetting;
|
||||
}
|
||||
|
||||
public List<String> getError_setting() {
|
||||
return errorSetting;
|
||||
}
|
||||
|
||||
public void setError_marker(String errorMarker) {
|
||||
this.errorMarker = errorMarker;
|
||||
}
|
||||
|
||||
public String getError_marker() {
|
||||
return errorMarker;
|
||||
}
|
||||
}
|
||||
43
src/main/java/org/ccalm/weather/models/PointModel.java
Normal file
43
src/main/java/org/ccalm/weather/models/PointModel.java
Normal file
@ -0,0 +1,43 @@
|
||||
package org.ccalm.weather.models;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class PointModel {
|
||||
|
||||
@JsonProperty("date")
|
||||
String date;
|
||||
@JsonProperty("hours")
|
||||
int hours;
|
||||
@JsonProperty("lon")
|
||||
double lon;
|
||||
@JsonProperty("lat")
|
||||
double lat;
|
||||
|
||||
public String getDate() {
|
||||
return date;
|
||||
}
|
||||
public void setDate(String date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public int getHours() {
|
||||
return hours;
|
||||
}
|
||||
public void setHours(int hours) {
|
||||
this.hours = hours;
|
||||
}
|
||||
|
||||
public double getLon() {
|
||||
return lon;
|
||||
}
|
||||
public void setLon(double lon) {
|
||||
this.lon = lon;
|
||||
}
|
||||
|
||||
public double getLat() {
|
||||
return lat;
|
||||
}
|
||||
public void setLat(double lat) {
|
||||
this.lat = lat;
|
||||
}
|
||||
}
|
||||
@ -163,6 +163,22 @@ public class Tools {
|
||||
return "";
|
||||
}
|
||||
|
||||
public static String CutBeforeFirst(StringBuffer str,String ch)
|
||||
{
|
||||
int pos=str.indexOf(ch);
|
||||
String result="";
|
||||
if(pos==-1)
|
||||
{
|
||||
result.concat(str.toString());
|
||||
str.delete(0,str.length());
|
||||
}else
|
||||
{
|
||||
result=str.substring(0,pos);
|
||||
str.delete(0,pos+1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
//узнать точку пересичений 2х линай если x=0 и y=0 то не пересиклась
|
||||
public static Point getCrossingLine(Point PHead0, Point PTail0, Point PHead1, Point PTail1)
|
||||
{
|
||||
|
||||
71
src/main/java/tools/CustomException.java
Normal file
71
src/main/java/tools/CustomException.java
Normal file
@ -0,0 +1,71 @@
|
||||
package tools;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.ccalm.weather.models.ErrorResponseModel;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public class CustomException extends Exception {
|
||||
private static final Logger logger = LogManager.getLogger(CustomException.class);
|
||||
|
||||
private ErrorResponseModel error;
|
||||
|
||||
public CustomException(int errorCode, String errorMessage, String marker) {
|
||||
super(errorMessage);
|
||||
error = new ErrorResponseModel(errorCode, errorMessage, marker);
|
||||
}
|
||||
|
||||
public CustomException(int errorCode, String errorMessage, String errorSetting, String marker) {
|
||||
super(errorMessage);
|
||||
error = new ErrorResponseModel(errorCode, errorMessage, errorSetting, marker);
|
||||
}
|
||||
|
||||
public CustomException(int errorCode, List<String> errorMessages, String marker) {
|
||||
super(String.join(" ", errorMessages));
|
||||
error = new ErrorResponseModel(errorCode, errorMessages, marker);
|
||||
}
|
||||
|
||||
public CustomException(int errorCode, List<String> errorMessages, List<String> errorSettings, String marker) {
|
||||
super(String.join(" ", errorMessages));
|
||||
error = new ErrorResponseModel(errorCode, errorMessages, errorSettings, marker);
|
||||
}
|
||||
|
||||
public int getErrorCode() {
|
||||
return error.getError_code();
|
||||
}
|
||||
|
||||
public String getErrorMarker() {
|
||||
return error.getError_marker();
|
||||
}
|
||||
|
||||
public List<String> getErrorMessages() {
|
||||
return error.getError_message();
|
||||
}
|
||||
|
||||
public List<String> getErrorSettings() {
|
||||
return error.getError_setting();
|
||||
}
|
||||
|
||||
public JSONObject getJson() {
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json.put("error_code", this.getErrorCode());
|
||||
json.put("error_message", this.getErrorMessages());
|
||||
json.put("error_setting", this.getErrorSettings());
|
||||
json.put("error_marker", this.getErrorMarker());
|
||||
} catch (JSONException e) {
|
||||
logger.error("Error", e);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
public ErrorResponseModel getErrorResponseModel() {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
@ -1,14 +1,24 @@
|
||||
package org.ccalm.weather;
|
||||
package tools;
|
||||
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.*;
|
||||
|
||||
public class DBTools {
|
||||
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DBTools.class);
|
||||
|
||||
//---------------------------------------------------------------------------
|
||||
public static Connection getConn(String url, String login, String password){
|
||||
Connection conn = null;
|
||||
try{
|
||||
Class.forName("org.postgresql.Driver");
|
||||
conn = DriverManager.getConnection(url,login,password);
|
||||
}catch(Exception ex)
|
||||
{
|
||||
logger.error("N1: "+ex.getMessage()+"<br>",ex);
|
||||
}
|
||||
return conn;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
public static String getCountryId(Statement st,double lon,double lat) {
|
||||
String country_id = "";
|
||||
30
src/main/java/tools/StdTools.java
Normal file
30
src/main/java/tools/StdTools.java
Normal file
@ -0,0 +1,30 @@
|
||||
package tools;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class StdTools {
|
||||
|
||||
//---------------------------------------------------------------------------
|
||||
private static final Logger logger = LogManager.getLogger(StdTools.class);
|
||||
|
||||
//---------------------------------------------------------------------------
|
||||
public JSONObject createJSONError(int code, String message, String setting, String marker) {
|
||||
JSONObject json = new JSONObject();
|
||||
try {
|
||||
json.put("error_code", code);
|
||||
json.put("error_message", Arrays.asList(message));
|
||||
json.put("error_setting", Arrays.asList(setting));
|
||||
json.put("error_marker", marker);
|
||||
} catch (JSONException e) {
|
||||
logger.error(e);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
//---------------------------------------------------------------------------
|
||||
|
||||
}
|
||||
BIN
src/main/resources/keystore.jks
Normal file
BIN
src/main/resources/keystore.jks
Normal file
Binary file not shown.
Reference in New Issue
Block a user