联网获取天气信息并保存到本地数据库

您所在的位置:网站首页 从数据库获取数据存到本地 联网获取天气信息并保存到本地数据库

联网获取天气信息并保存到本地数据库

2024-07-07 04:02| 来源: 网络整理| 查看: 265

自启动定时请求天气信息类,请求到的天气数据存储在本地数据库 

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.Date; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.http.HttpStatus; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.taiji.apps.base.utility.DateUtil; import com.taiji.apps.base.weather.domain.WeatherInfo; import com.taiji.apps.base.weather.service.WeatherService; /** * @ClassName:WeatherTimer定时请求天气信息类 * @Description:自启动定时请求天气信息类,请求到的天气数据存储在本地数据库 * @date:2017年5月27日 */ @Singleton @Startup public class WeatherTimer { @Resource TimerService timerService; @EJB public WeatherService weatherService; //存储到本地数据库,获取本地数据库数据 服务接口 private Date lastProgrammaticTimeout; //最后一次请求天气信息的时间 private Logger logger = LoggerFactory.getLogger(this.getClass()); //日志输出 /** * @Description: @PostConstruct注解自启动 * @date: 2017年5月27日 上午10:45:59 */ @PostConstruct public void init() { setTimer((long)60*60*1000); //设置定时执行频率:1小时 } /** * @Description: 调用定时器,启动定时器 * @param intervalDuration:定时执行频率 * @date: 2017年5月27日 上午10:47:26 */ public void setTimer(long intervalDuration) { logger.info("Setting a programmatic timeout for " + intervalDuration + " milliseconds from now."); TimerConfig timerConfig = new TimerConfig(); timerConfig.setPersistent(false); this.timerService.createIntervalTimer(5000, intervalDuration, timerConfig); } @Timeout public void programmaticTimeout(Timer timer) { logger.info("获取天气信息定时器已启动"); this.setLastProgrammaticTimeout(new Date()); if (tryConnection()) { getCurrentData(); getForecastData(); getAQIData(); } } /** * @Description: 通过url获取天气json * @param url 接口地址 * @return:天气json串 * @date: 2017年5月27日 上午10:55:07 */ private String getWeatherJson(String url) { try { URLConnection uc = new URL(url).openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8")); StringBuffer jsonBuffer = new StringBuffer(); String line = null; while (null != (line = reader.readLine())) { jsonBuffer.append(line); } return jsonBuffer.toString(); } catch (IOException e) { this.logger.error("通过" + url + "获取天气信息失败,原因如下:>>>>>>>>>>"+ e.getMessage()); return null; } } /** * @Description: 尝试连接URL指定网站 * @return:连接成功/失败 * @date: 2017年5月27日 上午10:57:05 */ public boolean tryConnection() { boolean flag = false; try { URL url = new URL("http://api.k780.com:88/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(1000); connection.setConnectTimeout(1000); if (HttpStatus.SC_OK == connection.getResponseCode()) { flag = true; } } catch (IOException e) { this.logger.error("天气信息接口http://api.k780.com:88/连接失败,原因如下:>>>>>>>>>>"+ e.getMessage()); } return flag; } /** * @Description: 获取当前天气 * @date: 2017年5月27日 上午11:00:05 */ private void getCurrentData() { String url = "http://api.k780.com:88/?app=weather.today&weaid=101030600" + "&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json"; String jsonStr = getWeatherJson(url); if (StringUtils.isNotBlank(jsonStr)) { JSONObject jsonObj = new JSONObject(jsonStr); String success = jsonObj.getString("success"); if ("1".equals(success)) { JSONObject result = jsonObj.getJSONObject("result"); SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd"); String todayStr = myFmt.format(new Date()); WeatherInfo tempWeather = this.weatherService.getWeatherInfoByDays(todayStr); if (null == tempWeather) { WeatherInfo weatherInfo = new WeatherInfo(); setCurrData(result, weatherInfo); } else { setCurrData(result, tempWeather); } } } } /** * @Description: 入库当前天气数据 * @param jsonObj jsonObj 当前天气的json对象 * @param weatherInfo: weatherInfo 天气对象 * @date: 2017年5月27日 上午11:01:16 */ private void setCurrData(JSONObject jsonObj, WeatherInfo weatherInfo) { if(StringUtils.isNotBlank(jsonObj.getString("days"))) { weatherInfo.setDays(jsonObj.getString("days")); } if(StringUtils.isNotBlank(jsonObj.getString("week"))) { weatherInfo.setWeek(jsonObj.getString("week")); } if(StringUtils.isNotBlank(jsonObj.getString("temperature_curr"))) { weatherInfo.setTemperatureCurr(jsonObj.getString("temperature_curr")); } if(StringUtils.isNotBlank(jsonObj.getString("weather_curr")) && (StringUtils.isNotBlank(jsonObj.getString("weather_icon")) || StringUtils.isNotBlank(jsonObj.getString("weather_icon1")))) { weatherInfo.setWeatherCurr(jsonObj.getString("weather_curr")); if(StringUtils.isNotBlank(jsonObj.getString("weather_icon"))) { weatherInfo.setWeatherIconCurr((jsonObj.getString("weather_icon"))); } else if(StringUtils.isNotBlank(jsonObj.getString("weather_icon1"))) { weatherInfo.setWeatherIconCurr(jsonObj.getString("weather_icon1")); } } if(StringUtils.isNotBlank(jsonObj.getString("wind"))) { weatherInfo.setWindCurr(jsonObj.getString("wind")); } if(StringUtils.isNotBlank(jsonObj.getString("winp"))) { weatherInfo.setWinpCurr(jsonObj.getString("winp")); } weatherInfo.setUpdateTime(new Date()); this.weatherService.saveWeatherInfo(weatherInfo); } /** * @Description: 获取未来七天天气 * @date: 2017年5月27日 上午11:01:47 */ private void getForecastData() { String url = "http://api.k780.com:88/?app=weather.future&weaid=101030600" + "&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json"; String jsonStr = getWeatherJson(url); if (StringUtils.isNotBlank(jsonStr)) { JSONObject jsonObj = new JSONObject(jsonStr); String success = jsonObj.getString("success"); if ("1".equals(success)) { JSONArray jsonArr = jsonObj.getJSONArray("result"); Date today = new Date(); String todayStr = DateUtil.format(today, DateUtil.datePattern); String tomorrowStr = DateUtil.format(DateUtil.getAfterDate(1), DateUtil.datePattern); String thirdStr = DateUtil.format(DateUtil.getAfterDate(2), DateUtil.datePattern); String fourthStr = DateUtil.format(DateUtil.getAfterDate(3), DateUtil.datePattern); String fifthStr = DateUtil.format(DateUtil.getAfterDate(4), DateUtil.datePattern); String sixthStr = DateUtil.format(DateUtil.getAfterDate(5), DateUtil.datePattern); String seventhStr = DateUtil.format(DateUtil.getAfterDate(6), DateUtil.datePattern); // 未来七天的日期字符串数组 String[] sevenDays = new String[] { todayStr, tomorrowStr, thirdStr, fourthStr, fifthStr, sixthStr, seventhStr }; for (int i = 0; i < jsonArr.length(); i++) { JSONObject tempJson = jsonArr.getJSONObject(i); // 解析并入库未来七天的天气 String days = tempJson.getString("days"); if (ArrayUtils.contains(sevenDays, days)) { setForecast(days, tempJson); } } } } } /** * @Description: 设置未来七天天气数据 * @param dayStr未来一天的日期串 * @param jsonObj:未来一天天气的json对象 * @date: 2017年5月27日 上午11:02:50 */ private void setForecast(String dayStr, JSONObject jsonObj) { WeatherInfo tempWeather = this.weatherService.getWeatherInfoByDays(dayStr); if(null==tempWeather) { WeatherInfo weatherInfo = new WeatherInfo(); setForData(jsonObj, weatherInfo); } else { setForData(jsonObj, tempWeather); } } /** * @Description: 入库未来七天天气数据 * @param jsonObj未来一天天气的json对象 * @param weatherInfo:天气对象 * @date: 2017年5月27日 上午11:03:41 */ private void setForData(JSONObject jsonObj, WeatherInfo weatherInfo) { if(StringUtils.isNotBlank(jsonObj.getString("days"))) { weatherInfo.setDays(jsonObj.getString("days")); } if(StringUtils.isNotBlank(jsonObj.getString("week"))) { weatherInfo.setWeek(jsonObj.getString("week")); } if(StringUtils.isNotBlank(jsonObj.getString("temperature"))) { weatherInfo.setTemperature(jsonObj.getString("temperature")); } if(StringUtils.isNotBlank(jsonObj.getString("weather")) && (StringUtils.isNotBlank(jsonObj.getString("weather_icon")) || StringUtils.isNotBlank(jsonObj.getString("weather_icon1")))) { weatherInfo.setWeather(jsonObj.getString("weather")); if(StringUtils.isNotBlank(jsonObj.getString("weather_icon"))) { weatherInfo.setWeatherIconD(jsonObj.getString("weather_icon")); } if(StringUtils.isNotBlank(jsonObj.getString("weather_icon1"))) { weatherInfo.setWeatherIconN(jsonObj.getString("weather_icon1")); } } if(StringUtils.isNotBlank(jsonObj.getString("wind"))) { weatherInfo.setWind(jsonObj.getString("wind")); } if(StringUtils.isNotBlank(jsonObj.getString("winp"))) { weatherInfo.setWinp(jsonObj.getString("winp")); } weatherInfo.setUpdateTime(new Date()); this.weatherService.saveWeatherInfo(weatherInfo); } /** * 获取当前空气指数AQI */ private void getAQIData() { String url = "http://api.k780.com:88/?app=weather.pm25&weaid=101030100" + "&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json"; String jsonStr = getWeatherJson(url); if (StringUtils.isNotBlank(jsonStr)) { JSONObject jsonObj = new JSONObject(jsonStr); String success = jsonObj.getString("success"); if ("1".equals(success)) { JSONObject result = jsonObj.getJSONObject("result"); SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd"); String todayStr = myFmt.format(new Date()); WeatherInfo tempWeather = this.weatherService .getWeatherInfoByDays(todayStr); if (null == tempWeather) { WeatherInfo weatherInfo = new WeatherInfo(); setAQIData(todayStr, result, weatherInfo); } else { setAQIData(todayStr, result, tempWeather); } } } } /** * 入库当前空气指数 * @param todayStr 今天日期串 * @param jsonObj 当前天气的json对象 * @param weatherInfo 天气对象 */ private void setAQIData(String todayStr, JSONObject jsonObj, WeatherInfo weatherInfo) { if(StringUtils.isBlank(weatherInfo.getDays())) { weatherInfo.setDays(todayStr); } if(StringUtils.isNotBlank(jsonObj.getString("aqi"))) { weatherInfo.setAqi(jsonObj.getString("aqi")); if(StringUtils.isNotBlank(jsonObj.getString("aqi_scope"))) { weatherInfo.setAqiScope(jsonObj.getString("aqi_scope")); } if(StringUtils.isNotBlank(jsonObj.getString("aqi_levid"))) { weatherInfo.setAqiLevid(jsonObj.getString("aqi_levid")); } if(StringUtils.isNotBlank(jsonObj.getString("aqi_levnm"))) { weatherInfo.setAqiLevnm(jsonObj.getString("aqi_levnm")); } if(StringUtils.isNotBlank(jsonObj.getString("aqi_remark"))) { weatherInfo.setAqiRemark(jsonObj.getString("aqi_remark")); } } weatherInfo.setUpdateTime(new Date()); this.weatherService.saveWeatherInfo(weatherInfo); } @PreDestroy private void destroy() { } public String getLastProgrammaticTimeout() { if (lastProgrammaticTimeout != null) { return lastProgrammaticTimeout.toString(); } else { return "never"; } } public void setLastProgrammaticTimeout(Date lastTimeout) { this.lastProgrammaticTimeout = lastTimeout; } }

天气对象实体类,存储在数据库中

import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.GenericGenerator; import com.taiji.framework.api.base.domain.BaseModel; /** * @ClassName:WeatherInfo 天气对象实体类 * @Description:天气对象实体类,存储在数据库中 * @date:2017年5月27日 */ @Entity @Table(name = "ES_WEATHER_INFO") public class WeatherInfo extends BaseModel implements Serializable { private static final long serialVersionUID = 1L; @Getter @Setter @Id @GeneratedValue(generator = "generator") @GenericGenerator(name = "generator", strategy = "uuid2") private String id; @Getter @Setter private String days; //日期 yyyy-MM-dd @Getter @Setter private String week; //星期 @Getter @Setter private String temperature; //气温 @Getter @Setter @Column(name = "TEMPERATURE_CURR") private String temperatureCurr; //当前气温 @Getter @Setter private String weather; //天气 @Getter @Setter @Column(name = "WEATHER_CURR") private String weatherCurr; //当前天气 @Getter @Setter @Column(name = "WEATHER_ICON_D") private String weatherIconD; //白天图标 @Getter @Setter @Column(name = "WEATHER_ICON_N") private String weatherIconN; //夜间图标 @Getter @Setter @Column(name = "WEATHER_ICON_CURR") private String weatherIconCurr; //当前图标 @Getter @Setter private String wind; //风向 @Getter @Setter @Column(name = "WIND_CURR") private String windCurr; //当前风向 @Getter @Setter private String winp; //风力 @Getter @Setter @Column(name = "WINP_CURR") private String winpCurr; //当前风力 @Getter @Setter private String aqi; //空气指数 @Getter @Setter @Column(name = "AQI_SCOPE") private String aqiScope; //指数范围 @Getter @Setter @Column(name = "AQI_LEVID") private String aqiLevid; //级别编号 @Getter @Setter @Column(name = "AQI_LEVNM") private String aqiLevnm; //级别 @Getter @Setter @Column(name = "AQI_REMARK") private String aqiRemark; //注意事项 @Getter @Setter @Column(name = "UPDATE_TIME") @Temporal(TemporalType.TIMESTAMP) private Date updateTime; //更新时间 public WeatherInfo(){ } @Override public Object retrieveId() { return this.id; } }

参考:http://blog.csdn.net/daydayupzzc/article/details/38866489  http://blog.csdn.net/u012204058/article/details/71034047



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3