GeoJSON by HTTP

This commit is contained in:
Igor I
2025-09-16 17:08:40 +05:00
parent 11d8e00bbc
commit 7fdf572d19
2 changed files with 179 additions and 12 deletions

View File

@ -10,8 +10,8 @@ spring:
application:
name: org-ccalm-main
datasource:
url: jdbc:postgresql://10.0.0.1:5432/CCALM?ApplicationName=org_ccalm_main&connectTimeout=10000&socketTimeout=30000
#url: jdbc:postgresql://ccalm.org:5432/CCALM?ApplicationName=org_ccalm_main&ssl=true&sslmode=require&connectTimeout=10000&socketTimeout=10000
#url: jdbc:postgresql://10.0.0.1:5432/CCALM?ApplicationName=org_ccalm_main&connectTimeout=10000&socketTimeout=30000
url: jdbc:postgresql://ccalm.org:5432/CCALM?ApplicationName=org_ccalm_main&ssl=true&sslmode=require&connectTimeout=10000&socketTimeout=10000
#url: jdbc:postgresql://127.0.0.1:5432/CCALM?ApplicationName=org_ccalm_main&ssl=true&sslmode=require&connectTimeout=10000&socketTimeout=10000
username: postgres
password: 309A86FF65A78FB428F4E38DFE35F730

View File

@ -7,23 +7,36 @@ import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
//import javax.servlet.ServletContext;
//import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jakarta.servlet.ServletContext;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.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;
@ -47,6 +60,19 @@ public class GeoGSON implements ServletContextAware {
@Value("${data.dir}")
String data_dir = "";
private final NamedParameterJdbcTemplate jdbcTemplate;
private final Environment environment;
private HikariDataSource dataSource;
//---------------------------------------------------------------------------
@Autowired
public GeoGSON(NamedParameterJdbcTemplate jdbcTemplate, HikariDataSource dataSource, Environment environment) {
this.jdbcTemplate = jdbcTemplate;
this.environment = environment;
this.dataSource = dataSource;
}
//---------------------------------------------------------------------------
@RequestMapping(value = {"/geojson", "/api/locust/v01/geojson"}, method = RequestMethod.GET)
@ResponseBody
public Object home(@RequestParam(required=false,name="table") String table,@RequestParam(required=false,name="id") String id)
@ -69,14 +95,14 @@ public class GeoGSON implements ServletContextAware {
error=true;
result="<br>SQLException: "+ex.getMessage()+"<br>";
}
if(!error)
{
Statement st;
try {
st = conn.createStatement();
String sql="select id,name,ST_AsGeoJSON(geom,3,0) as geom from main."+table+" where id="+id+";";
ResultSet rs = st.executeQuery(sql);
ResultSet rs = st.executeQuery(sql);
if(rs!=null)
{
while (rs.next())
@ -84,9 +110,9 @@ public class GeoGSON implements ServletContextAware {
String geom=null;
try {
geom=rs.getString("geom");
} catch( Exception ex )
} catch( Exception ex )
{
result="<metadata fn=\"-1\"><![CDATA[SQLException: "+ex.getMessage()+"]]></metadata>";
result="<metadata fn=\"-1\"><![CDATA[SQLException: "+ex.getMessage()+"]]></metadata>";
}
if(geom==null) geom="";
result=geom;
@ -96,7 +122,7 @@ public class GeoGSON implements ServletContextAware {
conn.close();
} catch (SQLException ex) {
result="<br>SQLException:"+ex.getMessage()+"<br>";
}
}
}
return result;
@ -107,7 +133,6 @@ public class GeoGSON implements ServletContextAware {
this.context=context;
}
//For compilatin android project
//http://127.0.0.1:8080/CCALM/countriesregionspoints
@RequestMapping(value = {"/countriesregionspoints", "/api/locust/v01/countriesregionspoints"}, method = RequestMethod.GET)
@ -226,4 +251,146 @@ public class GeoGSON implements ServletContextAware {
return result;
}
// JSON to file frmlocust_pods_density.qgs
@RequestMapping(
value = {"/gtest3","/geojson/frmlocust_pods_density", "/api/locust/v01/geojson/frmlocust_pods_density"},
method = RequestMethod.GET,
produces = "application/geo+json;charset=UTF-8"
)
@ResponseBody
public Object podsDensity(
@RequestParam(required = false, name = "country_id", defaultValue = "5") Integer countryId,
@RequestParam(required = false, name = "date_from", defaultValue = "1750227418") Long dateFromUnix,
@RequestParam(required = false, name = "date_to", defaultValue = "1758010618") Long dateToUnix,
@CookieValue(value = "lng", defaultValue = "1") String language_id
) {
try {
String sql = """
SELECT id,
--country_name,
--region_name,
--date,
COALESCE(pods,0) as pods,
ST_AsGeoJSON(geom) AS geometry
FROM main.view_frmlocust_pods_density
WHERE 1=1
AND geom IS NOT NULL
AND (:countryId IS NULL OR country_id = :countryId)
AND (:dateFrom IS NULL OR date >= to_timestamp(:dateFrom))
AND (:dateTo IS NULL OR date <= to_timestamp(:dateTo))
""";
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("countryId", countryId);
params.addValue("dateFrom", dateFromUnix);
params.addValue("dateTo", dateToUnix);
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, params);
// Формируем FeatureCollection
JSONArray features = new JSONArray();
for (Map<String, Object> row : rows) {
JSONObject feature = new JSONObject();
feature.put("type", "Feature");
// Геометрия
feature.put("geometry", new JSONObject((String) row.get("geometry")));
// Атрибуты
JSONObject props = new JSONObject();
for (Map.Entry<String, Object> e : row.entrySet()) {
if (!"geometry".equals(e.getKey())) {
props.put(e.getKey(), e.getValue());
}
}
feature.put("properties", props);
features.put(feature);
}
JSONObject collection = new JSONObject();
collection.put("type", "FeatureCollection");
collection.put("features", features);
return ResponseEntity.ok(collection.toString());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("{\"error\":\"" + e.getMessage() + "\"}");
}
}
@GetMapping(value = "/gtest", produces = "application/geo+json;charset=UTF-8")
@ResponseBody
public String getTestGeoJson() throws Exception {
ObjectMapper mapper = new ObjectMapper();
// Формируем GeoJSON как объект
String geoJson = """
{
"type": "FeatureCollection",
"features": [
{
"geometry": {
"coordinates": [70.15782, 42.2699],
"type": "Point"
},
"type": "Feature",
"properties": {
"date": "2025-09-13 17:55:00.0",
"country_name": "Kazakhstan (Қазақстан)",
"region_name": "Түркістан облысы (Туркестанская область)",
"pods": 0,
"id": 455603
}
},
{
"geometry": {
"coordinates": [70.15782, 42.2699],
"type": "Point"
},
"type": "Feature",
"properties": {
"date": "2025-09-13 17:55:00.0",
"country_name": "Kazakhstan (Қазақстан)",
"region_name": "Түркістан облысы (Туркестанская область)",
"pods": 0,
"id": 455602
}
}
]
}
""";
// Парсим и возвращаем для проверки корректности
return mapper.readTree(geoJson).toString();
}
@GetMapping(value = "/gtest2", produces = "application/geo+json;charset=UTF-8")
@ResponseBody
public String getTestGeoJson2() throws Exception {
ObjectMapper mapper = new ObjectMapper();
// Формируем GeoJSON как объект
String geoJson = """
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [70.15782, 42.2699]
},
"properties": {
"id": 1,
"name": "Test point"
}
}
]
}
""";
// Парсим и возвращаем для проверки корректности
return mapper.readTree(geoJson).toString();
}
}