Первый

This commit is contained in:
Igor I
2024-01-24 08:37:51 +06:00
commit 18d7a228f9
21 changed files with 2780 additions and 0 deletions

View File

@ -0,0 +1,432 @@
package org.ccalm.weather;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
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 javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.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 ucar.ma2.Array;
import ucar.nc2.Dimension;
import ucar.nc2.Variable;
import ucar.nc2.dataset.NetcdfDataset;
@Controller
public class AirTemperature implements ServletContextAware {
@Value("${custom.config.db_url}")
private String db_url;
@Value("${custom.config.db_login}")
private String db_login;
@Value("${custom.config.db_password}")
private String db_password;
@Value("${custom.config.data_dir}")
private String data_dir;
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SoilTmperature.class);
private ServletContext context;
//http://127.0.0.1:8080/AirTemperature
@RequestMapping(value = "/geodatalist/AirTemperature",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxTamer(/*@RequestParam(required=true,name="forecast") String forecast,*/@RequestParam(required=false,name="date") String date) {
String forecast = "000";
String result="";
result+="Start!<br>";
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
File dir = new File(data_dir+"temp"+File.separator);
if (!dir.exists()) dir.mkdirs();
//response.getWriter().append("Served at: ").append(request.getContextPath());
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url,db_login,db_password);
if(conn!=null)
{
logger.info("Connect is OK!");
result+="Connect is OK!<br>";
}else
{
logger.info("<br>Connect is ERROR<br>");
result+="Connect is ERROR!<br>";
}
}catch(Exception e)
{
logger.info("<br>Connect Exception:"+e.getMessage()+"<br>");
result+="Connect Exception:"+e.getMessage()+"<br>";
}
//Example request: http://ccalm.org/AirTemperature?date=20210531
//Example request: http://localhost:8080/AirTemperature?date=20210531
if(date==null || date.equals(""))
{
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
date=dateFormat.format(new Date()); //Date like as "20170327".
}
String time = "00"; //00 hours,06 hours,12 hours and 18 hours
String measurement = "TMP:2 m above ground";
//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()) {
System.out.println("Failed to delete the file \"air_text.idx\".");
}
}
WeatherDownload wd = new WeatherDownload();
if(wd.download(URL+".idx", data_dir+"temp"+File.separator+"air_text.idx", "0", ""))
{
result+="Download "+URL+".idx"+" to "+data_dir+"temp"+File.separator+"air_text.idx"+"<br>";
String strPos1="";
String strPos2="";
//Read file and find required line.
try {
BufferedReader br = new BufferedReader(new FileReader(data_dir+"temp"+File.separator+"air_text.idx"));
String line;
while ((line = br.readLine()) != null)
{
if (line.contains(measurement))
{
strPos1=line;
strPos2=br.readLine();
break;
}
}
br.close();
} catch (IOException ex) {
logger.info(ex.getMessage());
result+=ex.getMessage()+"<br>";
}
if(!strPos1.equals(""))
{
StringBuffer answer1=new StringBuffer(strPos1);
CutBeforeFirst(answer1,":");
String posStart = CutBeforeFirst(answer1,":");
StringBuffer answer2=new StringBuffer(strPos2);
CutBeforeFirst(answer2,":");
String posEnd = CutBeforeFirst(answer2,":");
if(posEnd==null || posEnd.equals("")) posEnd=""; else
{
posEnd=String.valueOf(Long.parseLong(posEnd)-1);
}
wd.download(URL, data_dir+"temp"+File.separator+"air_text.f000", String.valueOf(posStart), String.valueOf(posEnd));
}
}else
{
result+="Not download "+URL+".idx"+" to "+data_dir+"temp"+File.separator+"air_text.idx"+"<br>";
}
Array dataArrayLat=null;
Array dataArrayLon=null;
Array dataArrayTmp=null;
try {
// open netcdf/grib/grib2 file from argument
NetcdfDataset gid = NetcdfDataset.openDataset(data_dir+"temp"+File.separator+"air_text.f000");
//logger.info("Desc: " + gid.getDescription());
logger.info(gid.getDetailInfo());
//logger.info("Feature type: " + gid.getFeatureType().toString());
// get all grid tables in the file
List<Variable> variables = gid.getReferencedFile().getVariables();
for (int i = 0; i < variables.size(); i++)
{
String vName=variables.get(i).getName();
System.out.print(vName+" ");
if(vName.equals("reftime"))
{
logger.info("");
logger.info("Description = "+variables.get(i).getDescription());
logger.info("DimensionsString = "+variables.get(i).getDimensionsString());
logger.info("DataType = "+variables.get(i).getDataType());
logger.info("UnitsString = "+variables.get(i).getUnitsString()); //Hour since 2017-02-28T18:00:00Z
}
if(vName.equals("lon"))
{
dataArrayLon = variables.get(i).read();
}
if(vName.equals("lat"))
{
dataArrayLat = variables.get(i).read();
}
if(vName.equals("Temperature_height_above_ground"))
{
dataArrayTmp = variables.get(i).read();
}
}
logger.info("");
List<Dimension> dims = gid.getDimensions();
logger.info("dims.size() = " + dims.size());
Iterator<Dimension> dimIt = dims.iterator();
while( dimIt.hasNext()) {
Dimension dim = dimIt.next();
logger.info("Dim = " + dim);
logger.info("Dim name = "+dim.getName());
}
dimIt = null;
Statement st=null;
try {
st = conn.createStatement();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
try {
st.executeUpdate("BEGIN TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
result+="Size="+dataArrayLat.getSize()+"<br>";
//Delete old data
System.out.println("Delete old data 1");
try {
String sql="delete from main.air_temperature where date=cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone) and hours="+forecast;
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
System.out.println("Delete old data 2");
try {
String sql="delete from main.air_temperature where date<=CURRENT_DATE-'730 days'::INTERVAL";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
int pos=0;
for(int nLat=0;nLat<dataArrayLat.getSize();nLat++)
{
for(int nLon=0;nLon<dataArrayLon.getSize();nLon++)
{
//WGS84 Bounds: -180.0000, -90.0000, 180.0000, 90.0000
//Projected Bounds: -180.0000, -90.0000, 180.0000, 90.0000
double lon = dataArrayLon.getFloat(nLon);
if(lon>180) lon=lon-360;
double lat = dataArrayLat.getFloat(nLat);
if(lat>29 && lat<67 && lon>17 && lon<180) //Central Asia
{
if(!Float.isNaN(dataArrayTmp.getFloat(pos))) //On the water none temperatyre.
{
String country_id="";
ResultSet rs=null;
try {
String sql="select c.id from main.countries c where ST_Contains(c.geom,ST_SetSRID(st_makepoint("+lon+","+lat+"),4326)) limit 1";
rs = st.executeQuery(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
if (rs != null) {
try {
if (rs.next())
country_id=rs.getString(1);
rs.close();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
if(country_id!=null && !country_id.equals("") && !country_id.equals("null"))
{
//logger.info(lon + "," + lat +","+dataArrayTmp.getFloat(pos));
try {
String sql="insert into main.air_temperature(date,hours,val,geom,country_id)values(cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326),"+country_id+");";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
}
}
pos++;
}
}
//Cut data piece from big country of Russia
try {
String sql="update main.air_temperature w set country_id=null 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),w.geom);";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
//Delete values where country_id is null
try {
String sql="delete from main.air_temperature where country_id is null;";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
try {
st.executeUpdate("END TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
gid.close();
} catch (IOException ex) {
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.print("ERROR!");
}
try {conn.close();} catch (SQLException ex) {logger.info(ex.getMessage());}
result+="End!<br>";
return result;
}
//---------------------------------------------------------------------------
@Override
public void setServletContext(ServletContext context) {
this.context=context;
}
//---------------------------------------------------------------------------
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;
}
//---------------------------------------------------------------------------
//List of "Air temperature" dates from database in JSON
//@CacheControl(maxAge = 300)
@CrossOrigin
@RequestMapping(value = "/geodatalist/AirTemperatureDates",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxAirDates(HttpServletResponse response) {
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
response.addHeader("Cache-Control", headerValue);
boolean error=false;
String result="";
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
if (conn != null) {
logger.info("Connect is OK!");
} else {
error=true;
result="An error occurred while connecting to the database!";
}
} catch (Exception ex) {
logger.info(ex.getMessage());
error=true;
result="<br>SQLException: "+ex.getMessage()+"<br>";
}
if(!error)
{
Statement st;
try {
st = conn.createStatement();
String sql = "SELECT to_char(date, 'YYYY-MM-DD') as date,hours as hour,EXTRACT(DAY FROM CURRENT_DATE-date) as day FROM main.air_temperature group by date,hours order by date,hours;";
ResultSet rs = st.executeQuery(sql);
if(rs!=null)
{
boolean exists=false;
result="[";
while (rs.next())
{
exists=true;
try {
result+= "{\"num\":\""+rs.getString("day")+"\", \"hour\":\""+rs.getString("hour")+"\", \"date\":\""+rs.getString("date")+"\"},";
} catch( Exception ex )
{
}
}
if(exists) {
result=result.substring(0, result.length()-1);
result+="]";
}else {
result="[]";
}
}
st.close();
conn.close();
} catch (SQLException ex) {
result="<br>SQLException:"+ex.getMessage()+"<br>";
}
}
return result;
}
//---------------------------------------------------------------------------
}

View File

@ -0,0 +1,231 @@
package org.ccalm.weather;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.springframework.http.CacheControl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
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 tctable.Tools;
import javax.servlet.http.HttpServletResponse;
/*
* Server buffer for map tiles.
*/
@Controller
public class GeoTIFFList {
//---------------------------------------------------------------------------
public String dayofyear2date( int day ) {
//int day=Integer.parseInt(sDay)+1;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, day);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String result=format.format(calendar.getTime());
return result;
}
//---------------------------------------------------------------------------
public int[] setUnique(int[] array) {
int[] noDuplicates = IntStream.of(array).distinct().toArray();
return noDuplicates;
}
//---------------------------------------------------------------------------
public int[] toIntarray(Object[] obj){
int length = obj.length;
int intArray[] = new int[length];
for(int i=0; i<length; i++){
intArray[i] = (int) obj[i];
}
return intArray;
}
//---------------------------------------------------------------------------
//List GeoTIFF files
@CrossOrigin
@RequestMapping(value = "/geodatalist/GeoTIFF",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object geoTIFFData(HttpServletResponse response,@RequestParam(required=true,name="fn") String fn) {
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
response.addHeader("Cache-Control", headerValue);
String NDVIPath="/opt/tomcat/geoserver/ROOT/data/GeoTIFF/NDVI";
String NDWIPath="/opt/tomcat/geoserver/ROOT/data/GeoTIFF/NDWI";
String NDSIPath="/opt/tomcat/geoserver/ROOT/data/GeoTIFF/NDSI";
String SMAPPath="/opt/tomcat/geoserver/ROOT/data/GeoTIFF/SMAP";
String osName=System.getProperty("os.name");
if(osName.indexOf("Windows")>=0){
NDVIPath="O:\\temp\\CCALM\\NDVI";
NDWIPath="O:\\temp\\CCALM\\NDVI";
NDSIPath="O:\\temp\\CCALM\\NDVI";
SMAPPath="O:\\temp\\CCALM\\SMAP";
}
String result="";
if(fn.equals("ndvi_list")) {
List<Integer> arrlist = new ArrayList<Integer>();
String[] names;
File f = new File(NDVIPath);
names = f.list();
for (String name : names) {
if(Tools.afterLast(name,".").equals("json")){
String val=Tools.beforeFirst(name,".");
if(val.matches("\\d+")) {
arrlist.add(Integer.parseInt(val));
}
}
}
int[] data = setUnique(toIntarray(arrlist.toArray()));
Arrays.sort(data);
if(data.length>0) {
result="[";
for (int value : data){
result += "{\"num\":\""+ String.valueOf(value)+"\", \"date\":\""+dayofyear2date(value)+"\"},";
}
result=result.substring(0, result.length()-1);
result+=']';
}else {
result="[]";
}
}
if(fn.equals("ndwi_list")) {
List<Integer> arrlist = new ArrayList<Integer>();
File f = new File(NDWIPath);
String[] names = f.list();
for (String name : names) {
if(Tools.afterLast(name,".").equals("tiff")){
String val=Tools.beforeFirst(name,"_");
if(val.matches("\\d+")) {
arrlist.add(Integer.parseInt(val));
}else {
//Выбираю json с максимальным номером
int max=0;
File mf = new File(NDWIPath);
String[] mNames = mf.list();
for (String mName : mNames) {
String mVal=Tools.beforeFirst(mName,".");
if(mVal.matches("\\d+")) {
if(max<Integer.parseInt(mVal)) {
max=Integer.parseInt(mVal);
}
}
}
arrlist.add(max);
}
}
}
int[] data = setUnique(toIntarray(arrlist.toArray()));
Arrays.sort(data);
if(data.length>0) {
result="[";
for (int value : data){
result += "{\"num\":\""+ String.valueOf(value)+"\", \"date\":\""+dayofyear2date(value)+"\"},";
}
result=result.substring(0, result.length()-1);
result+=']';
}else {
result="[]";
}
}
if(fn.equals("ndsi_list")) {
List<Integer> arrlist = new ArrayList<Integer>();
File f = new File(NDSIPath);
String[] names = f.list();
for (String name : names) {
if(Tools.afterLast(name,".").equals("tiff")){
String val=Tools.beforeFirst(name,"_");
if(val.matches("\\d+")) {
arrlist.add(Integer.parseInt(val));
}else {
//Выбираю json с максимальным номером
int max=0;
File mf = new File(NDSIPath);
String[] mNames = mf.list();
for (String mName : mNames) {
String mVal=Tools.beforeFirst(mName,".");
if(mVal.matches("\\d+")) {
if(max<Integer.parseInt(mVal)) {
max=Integer.parseInt(mVal);
}
}
}
arrlist.add(max);
}
}
}
int[] data = setUnique(toIntarray(arrlist.toArray()));
Arrays.sort(data);
if(data.length>0) {
result="[";
for (int value : data){
result += "{\"num\":\""+ String.valueOf(value)+"\", \"date\":\""+dayofyear2date(value)+"\"},";
}
result=result.substring(0, result.length()-1);
result+=']';
}else {
result="[]";
}
}
if(fn.equals("smap_list")) {
List<Integer> arrlist = new ArrayList<Integer>();
File f = new File(SMAPPath);
String[] names = f.list();
for (String name : names) {
if(Tools.afterLast(name,".").equals("tiff")){
String val=Tools.beforeFirst(name,"_");
if(val.matches("\\d+")) {
arrlist.add(Integer.parseInt(val));
}else {
//Выбираю json с максимальным номером
int max=0;
File mf = new File(SMAPPath);
String[] mNames = mf.list();
for (String mName : mNames) {
String mVal=Tools.beforeFirst(mName,".");
if(mVal.matches("\\d+")) {
if(max<Integer.parseInt(mVal)) {
max=Integer.parseInt(mVal);
}
}
}
arrlist.add(max);
}
}
}
int[] data = setUnique(toIntarray(arrlist.toArray()));
Arrays.sort(data);
if(data.length>0) {
result="[";
for (int value : data){
result += "{\"num\":\""+ String.valueOf(value)+"\", \"date\":\""+dayofyear2date(value)+"\"},";
}
result=result.substring(0, result.length()-1);
result+=']';
}else {
result="[]";
}
}
return result;
}
}

View File

@ -0,0 +1,33 @@
package org.ccalm.weather;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
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;
@Controller
public class MainController {
@CrossOrigin
@GetMapping("/")
@ResponseBody
public String getIndex(Model model) {
return "The weather list is working! <br><a href=\"./geodatalist/\">/geodatalist/</a>";
}
@CrossOrigin
@GetMapping("/geodatalist")
@ResponseBody
public String getGeoDataList(Model model) {
String html="";
html+="<a href=\"./AirTemperatureDates\">AirTemperatureDates</a><br><form action=\"./AirTemperature\" method=\"get\"><label for=\"fname\">Date:</label><input type=\"text\" name=\"date\" value=\"20210826\"><input type=\"submit\" value=\"Submit\"></form><br>";
html+="<a href=\"./PrecipitationDates\">PrecipitationDates</a><br><form action=\"./Precipitation\" method=\"get\"><label for=\"fname\">Date:</label><input type=\"text\" name=\"date\" value=\"20210826\"><input type=\"submit\" value=\"Submit\"></form><br>";
html+="<a href=\"./SoilDates\">SoilDates</a><br><form action=\"./DownloadSoil\" method=\"get\"><label for=\"fname\">Date:</label><input type=\"text\" name=\"date\" value=\"20210826\"><label for=\"forecast\">Forecast:</label><input type=\"text\" name=\"forecast\" value=\"000\"><input type=\"submit\" value=\"Submit\"></form><br>";
return html;
}
}

View File

@ -0,0 +1,433 @@
package org.ccalm.weather;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
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 javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.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 ucar.ma2.Array;
import ucar.nc2.Dimension;
import ucar.nc2.Variable;
import ucar.nc2.dataset.NetcdfDataset;
@Controller
public class Precipitation implements ServletContextAware {
@Value("${custom.config.db_url}")
private String db_url;
@Value("${custom.config.db_login}")
private String db_login;
@Value("${custom.config.db_password}")
private String db_password;
@Value("${custom.config.data_dir}")
private String data_dir;
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SoilTmperature.class);
private ServletContext context;
//http://127.0.0.1:8080/AirTemperature
@RequestMapping(value = "/geodatalist/Precipitation",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxTamer(HttpServletResponse response,@RequestParam(required=false,name="date") String date) {
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
response.addHeader("Cache-Control", headerValue);
String forecast = "024";
String result="Start!<br>";
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
File dir = new File(data_dir+"temp"+File.separator);
if (!dir.exists()) dir.mkdirs();
//response.getWriter().append("Served at: ").append(request.getContextPath());
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url,db_login,db_password);
if(conn!=null)
{
logger.info("Connect is OK!");
result+="Connect is OK!<br>";
}else
{
logger.info("<br>Connect is ERROR<br>");
result+="Connect is ERROR!<br>";
}
}catch(Exception e)
{
logger.info("<br>Connect Exception:"+e.getMessage()+"<br>");
result+="Connect Exception:"+e.getMessage()+"<br>";
}
//Example request: http://localhost:8080/Precipitation?date=20210531
if(date==null || date.equals(""))
{
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
date=dateFormat.format(new Date()); //Date like as "20170327".
}
String time = "00"; //00 hours,06 hours,12 hours and 18 hours
String measurement = "APCP:surface:0-1 day acc fcst";
//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()) {
System.out.println("Failed to delete the file \"pre_text.idx\".");
}
}
WeatherDownload wd = new WeatherDownload();
if(wd.download(URL+".idx", data_dir+"temp"+File.separator+"pre_text.idx", "0", ""))
{
result+="Download "+URL+".idx"+" to "+data_dir+"temp"+File.separator+"pre_text.idx"+"<br>";
System.out.println("Download "+URL+".idx"+" to "+data_dir+"temp"+File.separator+"pre_text.idx"+"<br>");
String strPos1="";
String strPos2="";
//Read file and find required line.
try {
BufferedReader br = new BufferedReader(new FileReader(data_dir+"temp"+File.separator+"pre_text.idx"));
String line;
while ((line = br.readLine()) != null)
{
if (line.contains(measurement))
{
strPos1=line;
strPos2=br.readLine();
break;
}
}
br.close();
} catch (IOException ex) {
logger.info(ex.getMessage());
result+=ex.getMessage()+"<br>";
}
if(!strPos1.equals(""))
{
StringBuffer answer1=new StringBuffer(strPos1);
CutBeforeFirst(answer1,":");
String posStart = CutBeforeFirst(answer1,":");
StringBuffer answer2=new StringBuffer(strPos2);
CutBeforeFirst(answer2,":");
String posEnd = CutBeforeFirst(answer2,":");
if(posEnd==null || posEnd.equals("")) posEnd=""; else
{
posEnd=String.valueOf(Long.parseLong(posEnd)-1);
}
wd.download(URL, data_dir+"temp"+File.separator+"pre_text.f000", String.valueOf(posStart), String.valueOf(posEnd));
}
}else
{
result+="Not download "+URL+".idx"+" to "+data_dir+"temp"+File.separator+"pre_text.idx"+"<br>";
}
Array dataArrayLat=null;
Array dataArrayLon=null;
Array dataArrayTmp=null;
try {
// open netcdf/grib/grib2 file from argument
NetcdfDataset gid = NetcdfDataset.openDataset(data_dir+"temp"+File.separator+"pre_text.f000");
//logger.info("Desc: " + gid.getDescription());
logger.info(gid.getDetailInfo());
//logger.info("Feature type: " + gid.getFeatureType().toString());
// get all grid tables in the file
List<Variable> variables = gid.getReferencedFile().getVariables();
for (int i = 0; i < variables.size(); i++)
{
String vName=variables.get(i).getName();
System.out.print(vName+" ");
if(vName.equals("reftime"))
{
logger.info("");
logger.info("Description = "+variables.get(i).getDescription());
logger.info("DimensionsString = "+variables.get(i).getDimensionsString());
logger.info("DataType = "+variables.get(i).getDataType());
logger.info("UnitsString = "+variables.get(i).getUnitsString()); //Hour since 2017-02-28T18:00:00Z
}
if(vName.equals("lon"))
{
dataArrayLon = variables.get(i).read();
}
if(vName.equals("lat"))
{
dataArrayLat = variables.get(i).read();
}
if(vName.equals("Total_precipitation_surface_24_Hour_Accumulation"))
{
dataArrayTmp = variables.get(i).read();
}
}
logger.info("");
List<Dimension> dims = gid.getDimensions();
logger.info("dims.size() = " + dims.size());
Iterator<Dimension> dimIt = dims.iterator();
while( dimIt.hasNext()) {
Dimension dim = dimIt.next();
logger.info("Dim = " + dim);
logger.info("Dim name = "+dim.getName());
}
dimIt = null;
Statement st=null;
try {
st = conn.createStatement();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
try {
st.executeUpdate("BEGIN TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
result+="Size="+dataArrayLat.getSize()+"<br>";
//Delete old data
System.out.println("Delete old data 1");
try {
String sql="delete from main.precipitation where date=cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone) and hours="+forecast;
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
System.out.println("Delete old data 2");
try {
String sql="delete from main.precipitation where date<=CURRENT_DATE-'730 days'::INTERVAL";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
int pos=0;
for(int nLat=0;nLat<dataArrayLat.getSize();nLat++)
{
for(int nLon=0;nLon<dataArrayLon.getSize();nLon++)
{
//WGS84 Bounds: -180.0000, -90.0000, 180.0000, 90.0000
//Projected Bounds: -180.0000, -90.0000, 180.0000, 90.0000
double lon = dataArrayLon.getFloat(nLon);
if(lon>180) lon=lon-360;
double lat = dataArrayLat.getFloat(nLat);
if(lat>29 && lat<67 && lon>17 && lon<180) //Central Asia
{
if(!Float.isNaN(dataArrayTmp.getFloat(pos))) //On the water none temperatyre.
{
String country_id="";
ResultSet rs=null;
try {
rs = st.executeQuery("select c.id from main.countries c where ST_Contains(c.geom,ST_SetSRID(st_makepoint("+lon+","+lat+"),4326)) limit 1");
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
if (rs != null) {
try {
if (rs.next())
country_id=rs.getString(1);
rs.close();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
if(country_id!=null && !country_id.equals("") && !country_id.equals("null"))
{
//logger.info(lon + "," + lat +","+dataArrayTmp.getFloat(pos));
try {
String sql="insert into main.precipitation(date,hours,val,geom,country_id)values(cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326),"+country_id+");";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
}
}
pos++;
}
}
//Cut data piece from big country of Russia
try {
String sql="update main.precipitation w set country_id=null 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),w.geom);";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
//Delete values where country_id is null
try {
String sql="delete from main.precipitation where country_id is null;";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
try {
st.executeUpdate("END TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
gid.close();
} catch (IOException ex) {
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.print("ERROR!");
}
try {conn.close();} catch (SQLException ex) {logger.info(ex.getMessage());}
result+="End!<br>";
return result;
}
//---------------------------------------------------------------------------
@Override
public void setServletContext(ServletContext context) {
this.context=context;
}
//---------------------------------------------------------------------------
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;
}
//---------------------------------------------------------------------------
//List of "Air temperature" dates from database in JSON
@CrossOrigin
@RequestMapping(value = "/geodatalist/PrecipitationDates",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxAirDates(HttpServletResponse response) {
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
response.addHeader("Cache-Control", headerValue);
boolean error=false;
String result="";
//Load DB configuration from "config.xml"
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
if (conn != null) {
logger.info("Connect is OK!");
} else {
error=true;
result="An error occurred while connecting to the database!";
}
} catch (Exception ex) {
logger.info(ex.getMessage());
error=true;
result="<br>SQLException: "+ex.getMessage()+"<br>";
}
if(!error)
{
Statement st;
try {
st = conn.createStatement();
String sql = "SELECT to_char(date, 'YYYY-MM-DD') as date,hours as hour,DATE_PART('doy',date)-1 as day FROM main.precipitation group by date,hours order by date,hours";
ResultSet rs = st.executeQuery(sql);
if(rs!=null)
{
boolean exists=false;
result="[";
while (rs.next())
{
exists=true;
try {
result+= "{\"num\":\""+rs.getString("day")+"\", \"hour\":\""+rs.getString("hour")+"\", \"date\":\""+rs.getString("date")+"\"},";
} catch( Exception ex )
{
}
}
if(exists) {
result=result.substring(0, result.length()-1);
result+="]";
}else {
result="[]";
}
}
st.close();
conn.close();
} catch (SQLException ex) {
result="<br>SQLException:"+ex.getMessage()+"<br>";
}
}
return result;
}
//---------------------------------------------------------------------------
}

View File

@ -0,0 +1,458 @@
package org.ccalm.weather;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
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 javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.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 ucar.ma2.Array;
import ucar.nc2.Dimension;
import ucar.nc2.Variable;
import ucar.nc2.dataset.NetcdfDataset;
@Controller
public class SoilTmperature implements ServletContextAware {
@Value("${custom.config.db_url}")
private String db_url;
@Value("${custom.config.db_login}")
private String db_login;
@Value("${custom.config.db_password}")
private String db_password;
@Value("${custom.config.data_dir}")
private String data_dir;
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SoilTmperature.class);
private ServletContext context;
//Example: http://127.0.0.1:8081/geodatalist/DownloadSoil?forecast=000
@RequestMapping(value = "/geodatalist/DownloadSoil",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxTamer(HttpServletResponse response,@RequestParam(required=true,name="forecast") String forecast,@RequestParam(required=false,name="date") String date) {
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
response.addHeader("Cache-Control", headerValue);
//String forecast = request.getParameter("forecast"); //Date like as "000".
//response.setContentType("text/html");
//PrintWriter out = response.getWriter();
String result="";
result+="Start!<br>";
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
File dir = new File(data_dir+"temp"+File.separator);
if (!dir.exists()) dir.mkdirs();
//response.getWriter().append("Served at: ").append(request.getContextPath());
Connection conn = null;
try{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url,db_login,db_password);
if(conn!=null)
{
logger.info("Connect is OK!");
result+="Connect is OK!<br>";
}else
{
logger.info("<br>Connect is ERROR<br>");
result+="Connect is ERROR!<br>";
}
}catch(Exception e)
{
logger.info("<br>Connect Exception:"+e.getMessage()+"<br>");
result+="Connect Exception:"+e.getMessage()+"<br>";
}
//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(""))
{
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
date=dateFormat.format(new Date()); //Date like as "20170327".
}
//Parameter Table Version 2: https://www.nco.ncep.noaa.gov/pmb/docs/on388/table2.html
String time = "00"; //00 hours,06 hours,12 hours and 18 hours
//String forecast = request.getParameter("forecast"); //Date like as "000".
String measurement = "TSOIL:0-0.1 m below ground";
//String measurement = "TSOIL:0.1-0.4 m below ground";
//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()) {
System.out.println("Failed to delete the file \"text.idx\".");
}
}
WeatherDownload wd = new WeatherDownload();
if(wd.download(URL+".idx", data_dir+"temp"+File.separator+"text.idx", "0", ""))
{
result+="Download "+URL+".idx"+" to "+data_dir+"temp"+File.separator+"text.idx"+"<br>";
String strPos1="";
String strPos2="";
//Read file and find required line.
try {
BufferedReader br = new BufferedReader(new FileReader(data_dir+"temp"+File.separator+"text.idx"));
String line;
while ((line = br.readLine()) != null)
{
//if (line.contains("TSOIL:0-0.1 m below ground"))
if (line.contains(measurement))
{
strPos1=line;
strPos2=br.readLine();
break;
}
}
br.close();
} catch (IOException ex) {
logger.info(ex.getMessage());
result+=ex.getMessage()+"<br>";
}
if(!strPos1.equals(""))
{
//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,":");
StringBuffer answer2=new StringBuffer(strPos2);
CutBeforeFirst(answer2,":");
String posEnd = CutBeforeFirst(answer2,":");
if(posEnd==null || posEnd.equals("")) posEnd=""; else
{
posEnd=String.valueOf(Long.parseLong(posEnd)-1);
}
wd.download(URL, data_dir+"temp"+File.separator+"text.f000", String.valueOf(posStart), String.valueOf(posEnd));
}
}else
{
result+="Not download "+URL+".idx"+" to "+data_dir+"temp"+File.separator+"text.idx"+"<br>";
}
Array dataArrayLat=null;
Array dataArrayLon=null;
Array dataArrayTmp=null;
try {
// open netcdf/grib/grib2 file from argument
NetcdfDataset gid = NetcdfDataset.openDataset(data_dir+"temp"+File.separator+"text.f000");
//logger.info("Desc: " + gid.getDescription());
logger.info(gid.getDetailInfo());
//logger.info("Feature type: " + gid.getFeatureType().toString());
// get all grid tables in the file
List<Variable> variables = gid.getReferencedFile().getVariables();
for (int i = 0; i < variables.size(); i++)
{
System.out.print(variables.get(i).getName()+" ");
//LatLon_Projection, lat, lon, reftime, time, depth_below_surface_layer, depth_below_surface_layer_bounds, Soil_temperature_depth_below_surface_layer
if(variables.get(i).getName().equals("reftime"))
{
logger.info("");
logger.info("Description = "+variables.get(i).getDescription());
logger.info("DimensionsString = "+variables.get(i).getDimensionsString());
logger.info("DataType = "+variables.get(i).getDataType());
logger.info("UnitsString = "+variables.get(i).getUnitsString()); //Hour since 2017-02-28T18:00:00Z
}
if(variables.get(i).getName().equals("lon"))
{
dataArrayLon = variables.get(i).read();
}
if(variables.get(i).getName().equals("lat"))
{
dataArrayLat = variables.get(i).read();
}
if(variables.get(i).getName().equals("Soil_temperature_depth_below_surface_layer"))
{
//Section sec=new Section();
dataArrayTmp = variables.get(i).read();
/*for(int j=0;j<dataArrayTmp.getSize();j++)
{
logger.info(j+") "+dataArrayTmp.getFloat(j)+",");
}*/
}
}
logger.info("");
List<Dimension> dims = gid.getDimensions();
logger.info("dims.size() = " + dims.size());
Iterator<Dimension> dimIt = dims.iterator();
while( dimIt.hasNext()) {
Dimension dim = dimIt.next();
logger.info("Dim = " + dim);
logger.info("Dim name = "+dim.getName());
}
dimIt = null;
Statement st=null;
try {
st = conn.createStatement();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
try {
st.executeUpdate("BEGIN TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
result+="Size="+dataArrayLat.getSize()+"<br>";
//Delete old data
System.out.println("Delete old data 1");
try {
String sql="delete from main.soil_temperature where date=cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone) and hours="+forecast;
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
System.out.println("Delete old data 2");
try {
String sql="delete from main.soil_temperature where date<=CURRENT_DATE-'730 days'::INTERVAL";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
if(Integer.parseInt(forecast)!=0) {
System.out.println("Delete old data 3");
try {
String sql="delete from main.soil_temperature where hours="+forecast;
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
int pos=0;
for(int nLat=0;nLat<dataArrayLat.getSize();nLat++)
{
for(int nLon=0;nLon<dataArrayLon.getSize();nLon++)
{
//WGS84 Bounds: -180.0000, -90.0000, 180.0000, 90.0000
//Projected Bounds: -180.0000, -90.0000, 180.0000, 90.0000
double lon = dataArrayLon.getFloat(nLon);
if(lon>180) lon=lon-360;
double lat = dataArrayLat.getFloat(nLat);
if(lat>29 && lat<67 && lon>17 && lon<180) //Central Asia
{
if(!Float.isNaN(dataArrayTmp.getFloat(pos))) //On the water none temperatyre.
{
String country_id="";
ResultSet rs=null;
try {
rs = st.executeQuery("select c.id from main.countries c where ST_Contains(c.geom,ST_SetSRID(st_makepoint("+lon+","+lat+"),4326)) limit 1");
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
if (rs != null) {
try {
if (rs.next())
country_id=rs.getString(1);
rs.close();
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
if(country_id!=null && !country_id.equals("") && !country_id.equals("null"))
{
//logger.info(lon + "," + lat +","+dataArrayTmp.getFloat(pos));
try {
//String sql="insert into main.soil_temperature(weather_type_id,date,hours,val,geom)values(1,cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326));";
//String sql="insert into main.soil_temperature(weather_type_id,date,hours,val,geom,country_id)values(1,cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326),(select c.id from main.countries c where ST_Contains(c.geom,ST_SetSRID(st_makepoint("+lon+","+lat+"),4326)) limit 1));";
String sql="insert into main.soil_temperature(date,hours,val,geom,country_id)values(cast(to_timestamp('"+date+" "+time+"', 'YYYYMMDD HH24') as timestamp without time zone),"+forecast+","+dataArrayTmp.getFloat(pos)+",ST_SetSRID(st_makepoint("+lon+","+lat+"),4326),"+country_id+");";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
}
}
}
pos++;
}
}
//Cut data piece from big country of Russia
try {
String sql="update main.soil_temperature w set country_id=null 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),w.geom);";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
//Delete values where country_id is null
try {
String sql="delete from main.soil_temperature where country_id is null;";
st.executeUpdate(sql);
} catch (SQLException ex) {
logger.info(ex.getMessage());
}
try {
st.executeUpdate("END TRANSACTION;");
} catch (SQLException ex) {
logger.info(ex.getMessage());
logger.info(ex.getMessage());
}
gid.close();
} catch (IOException ex) {
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
System.out.print("ERROR!");
}
try {conn.close();} catch (SQLException ex) {logger.info(ex.getMessage());}
result+="End!<br>";
return result;
}
//---------------------------------------------------------------------------
@Override
public void setServletContext(ServletContext context) {
this.context=context;
}
//---------------------------------------------------------------------------
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;
}
//---------------------------------------------------------------------------
//List of "Soil temperature" dates from database in JSON
@CrossOrigin
@RequestMapping(value = "/geodatalist/SoilDates",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
@ResponseBody
public Object ajaxSoilDates(HttpServletResponse response) {
String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
response.addHeader("Cache-Control", headerValue);
boolean error=false;
String result="";
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(db_url, db_login, db_password);
if (conn != null) {
logger.info("Connect is OK!");
} else {
error=true;
result="An error occurred while connecting to the database!";
}
} catch (Exception ex) {
logger.info(ex.getMessage());
error=true;
result="<br>SQLException: "+ex.getMessage()+"<br>";
}
if(!error)
{
Statement st;
try {
st = conn.createStatement();
String sql = "SELECT to_char(date, 'YYYY-MM-DD') as date,hours as hour,EXTRACT(DAY FROM CURRENT_DATE-date) as day FROM main.soil_temperature group by date,hours order by date,hours";
ResultSet rs = st.executeQuery(sql);
if(rs!=null)
{
boolean exists=false;
result="[";
while (rs.next())
{
exists=true;
try {
result+= "{\"num\":\""+rs.getString("day")+"\", \"hour\":\""+rs.getString("hour")+"\", \"date\":\""+rs.getString("date")+"\"},";
} catch( Exception ex )
{
}
}
if(exists) {
result=result.substring(0, result.length()-1);
result+="]";
}else {
result="[]";
}
}
st.close();
conn.close();
} catch (SQLException ex) {
result="<br>SQLException:"+ex.getMessage()+"<br>";
}
}
return result;
}
//---------------------------------------------------------------------------
}

View File

@ -0,0 +1,13 @@
package org.ccalm.weather;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WeatherApplication {
public static void main(String[] args) {
SpringApplication.run(WeatherApplication.class, args);
}
}

View File

@ -0,0 +1,126 @@
package org.ccalm.weather;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* @author ivanov.i
*/
public class WeatherDownload {
private static final int BUFFER_SIZE = 4096;
public boolean download(String strURL,String strFile,String posStart,String posEnd)
{
boolean result=true;
String rez = null;
String inputLine = null;
/*try
{
rez = new String("".getBytes(), "utf-8");
inputLine = new String("".getBytes(), "utf-8");
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}*/
try
{
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Range","bytes=" + posStart + "-" + posEnd);
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode / 100 == 2) //Code 206 is "Partial Content"
{
InputStream inputStream = conn.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);
}
outputStream.close();
inputStream.close();
}
conn.disconnect();
}
catch (IOException e)
{
//e.printStackTrace();
result=false;
}
return result;
}
/**
* Downloads a file from a URL
* @param fileURL HTTP URL of the file to be downloaded
* @param saveDir path of the directory to save the file
* @throws IOException
*/
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}

View File

@ -0,0 +1,14 @@
/**
* Created by IntelliJ IDEA.
* User: igor
* Date: 09.03.2007
* Time: 0:53:45
* To change this template use File | Settings | File Templates.
*/
package tctable;
public class Point
{
public double x=0;
public double y=0;
}

View File

@ -0,0 +1,273 @@
package tctable;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.TimeZone;
public class Tools {
public static String readStringFromInputStream(InputStream inputStream) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
try {
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
} catch (IOException e1) {
e1.printStackTrace();
}
// StandardCharsets.UTF_8.name() > JDK 7
try {
return result.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
}
return "";
}
//Преобразовать арабские и индийские в современные цифры
public static String numConvert(String str)
{
if(str==null) return null;
String persian = "۰۱۲۳۴۵۶۷۸۹";
String arabic = "٩٨٧٦٥٤٣٢١٠";
String num = "0123456789";
//Заменяю персидские
for(int i=0;i<str.length();i++)
{
for(int j=0;j<persian.length();j++)
{
if(str.charAt(i)==persian.charAt(j))
{
str = str.substring(0,i) + num.charAt(j) + str.substring(i+1);
break;
}
}
}
//Заменяю арабские
for(int i=0;i<str.length();i++)
{
for(int j=0;j<arabic.length();j++)
{
if(str.charAt(i)==arabic.charAt(j))
{
str = str.substring(0,i) + num.charAt(j) + str.substring(i+1);
break;
}
}
}
return str;
}
//Получить бит по его номеру нумерация лева на право
public static boolean getBit(byte[] mas, int pos)
{
int n=(int) Math.floor(pos/8.0);
int b=mas[n];
pos=pos - n * 8;
if(((b << pos) & 128) == 128)
return true;
else
return false;
}
//Установить 1й бит в номер нумерация с лева на право
public static void setBit(byte[] mas, int pos)
{
int n=(int) Math.floor(pos/8.0);
pos=pos - n * 8;
mas[n] = (byte)(mas[n] | (128 >> pos));
}
public static String readUTF8_1(InputStream handle) throws IOException
{
byte[] tmp=new byte[handle.read()];
handle.read(tmp);
return new String(tmp, "UTF8");
}
public static float readFloat(DataInputStream InStream) throws IOException
{
float f;
int ch1, ch2, ch3, ch4, count;
ch1 = InStream.readUnsignedByte();
ch2 = InStream.readUnsignedByte();
ch3 = InStream.readUnsignedByte();
ch4 = InStream.readUnsignedByte();
count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
f = Float.intBitsToFloat(count);
return f;
}
public static int readInt(DataInputStream InStream) throws IOException
{
int ch1, ch2, ch3, ch4, count;
ch1 = InStream.readUnsignedByte();
ch2 = InStream.readUnsignedByte();
ch3 = InStream.readUnsignedByte();
ch4 = InStream.readUnsignedByte();
count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1;
return count;
}
public static short readShort(DataInputStream InStream) throws IOException
{
int ch1, ch2, count;
ch1 = InStream.readUnsignedByte();
ch2 = InStream.readUnsignedByte();
count = (ch2 << 8) | ch1;
return (short)count;
}
public static int readUShort(InputStream InStream) throws IOException
{
int ch1, ch2;
ch1 = InStream.read();
ch2 = InStream.read();
return (ch2 << 8) | ch1;
}
public static String afterLast(String str, String ch)
{
int i=str.lastIndexOf(ch);
if(i!=-1)
{
return str.substring(i+ch.length());
}
return "";
}
public static String beforeLast(String str, String ch)
{
int i=str.lastIndexOf(ch);
if(i!=-1)
{
return str.substring(0,i);
}
return "";
}
public static String beforeFirst(String str, String ch)
{
int i=str.indexOf(ch);
if(i!=-1)
{
return str.substring(0,i);
}
return "";
}
//узнать точку пересичений 2х линай если x=0 и y=0 то не пересиклась
public static Point getCrossingLine(Point PHead0, Point PTail0, Point PHead1, Point PTail1)
{
Point rezPoint = new Point();
double a0, b0, c0, a1, b1, c1;
boolean bRez = true;
a0 = PTail0.y - PHead0.y;
b0 = PHead0.x - PTail0.x;
c0 = PTail0.x * PHead0.y - PHead0.x * PTail0.y;
a1 = PTail1.y - PHead1.y;
b1 = PHead1.x - PTail1.x;
c1 = PTail1.x * PHead1.y - PHead1.x * PTail1.y;
if (b1 == 0) rezPoint.x = PHead1.x;//если перпендикулярна oy
else rezPoint.x = (-(b0 * c1 / b1) + c0) / ((b0 * a1 / b1) - a0);
if (a1 == 0) rezPoint.y = PHead1.y;//если перпендикулярна oy
else rezPoint.y = (-(c1 * a0 / a1) + c0) / ((a0 * b1 / a1) - b0);
//проверка на вхождение в отрезоки (с погрешностью 0.0000001 (зачем понадобилась погрешность?))
//по x
if ((rezPoint.x < Math.min(PHead0.x, PTail0.x) - 0.0000001) || (rezPoint.x > Math.max(PHead0.x, PTail0.x) + 0.0000001))
bRez = false;
if ((rezPoint.x < Math.min(PHead1.x, PTail1.x) - 0.0000001) || (rezPoint.x > Math.max(PHead1.x, PTail1.x) + 0.0000001))
bRez = false;
//по y
if ((rezPoint.y < Math.min(PHead0.y, PTail0.y) - 0.0000001) || (rezPoint.y > Math.max(PHead0.y, PTail0.y) + 0.0000001))
bRez = false;
if ((rezPoint.y < Math.min(PHead1.y, PTail1.y) - 0.0000001) || (rezPoint.y > Math.max(PHead1.y, PTail1.y) + 0.0000001))
bRez = false;
if (!bRez)
{
rezPoint.x = 0;
rezPoint.y = 0;
}
return rezPoint;
}
public static Point getCrossingLine2(Point PHead0,Point PTail0,Point PHead1,Point PTail1)
{
boolean bRez=true;
Point rezPoint = new Point();
rezPoint.x=0;
rezPoint.y=0;
double a0,b0,c0,a1,b1,c1;
a0=PTail0.y-PHead0.y;
b0=PHead0.x-PTail0.x;
c0=PTail0.x*PHead0.y-PHead0.x*PTail0.y;
a1=PTail1.y-PHead1.y;
b1=PHead1.x-PTail1.x;
c1=PTail1.x*PHead1.y-PHead1.x*PTail1.y;
if (b1==0) rezPoint.x=PHead1.x;//если перпендикулярна oy
else rezPoint.x=(-(b0*c1/b1)+c0)/((b0*a1/b1)-a0);
if (a1==0) rezPoint.y=PHead1.y;//если перпендикулярна ox
else rezPoint.y=(-(c1*a0/a1)+c0)/((a0*b1/a1)-b0);
//по x
if (rezPoint.x<Math.min(PHead0.x,PTail0.x)||rezPoint.x>Math.max(PHead0.x,PTail0.x))
bRez=false;
if (rezPoint.x<Math.min(PHead1.x,PTail1.x)||rezPoint.x>Math.max(PHead1.x,PTail1.x))
bRez=false;
//по y
if (rezPoint.y<Math.min(PHead0.y,PTail0.y)||rezPoint.y>Math.max(PHead0.y,PTail0.y))
bRez=false;
if (rezPoint.y<Math.min(PHead1.y,PTail1.y)||rezPoint.y>Math.max(PHead1.y,PTail1.y))
bRez=false;
if (!bRez)
{
rezPoint.x=0;
rezPoint.y=0;
}
return rezPoint;
}
//Так как в replaceAll много заморочек с регулярными выражениями
public static String replaceAll(String txt, String val, String rep) {
if(txt==null || val==null || rep==null) return txt;
return txt.replace(val,rep);
/*while(true)
{
String tmpstr=txt.replace(val, rep);
if(tmpstr.equals(txt))
{
txt=tmpstr;
break;
}else
{
txt=tmpstr;
}
}
return txt;*/
}
public static byte[] subArray(byte[] b, int offset, int length) {
byte[] sub = new byte[length];
for (int i = offset; i < offset + length; i++) {
try {
sub[i - offset] = b[i];
} catch (Exception e) {
}
}
return sub;
}
}