微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

webservice 获取天气情况

----JOB获取天气情况: 1、job配置: <?xml version="1.0" encoding="UTF-8"?> <quartz>     <!-- 自动获取天气预报 -->     <job>         <job-detail>             <name>WeatherJob</name>             <group>WeatherJobGroup</group>             <description>定时获取天气任务</description>             <job-class>com.coship.createPortal.weather.job.WeatherJob</job-class>         </job-detail>         <trigger>             <cron>                 <name>WeatherJobCron</name>                 <group>WeatherJobGroup</group>                 <job-name>WeatherJob</job-name>                 <job-group>WeatherJobGroup</job-group>                 <cron-expression>0 0/2 * * * ?</cron-expression>             </cron>         </trigger>     </job> </quartz> 2、处理类实现: package com.xxxx.createPortal.weather.job; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.http.httpentity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.springframework.web.context.ContextLoader; import com.xxxx.ChineseCharacter; import com.xxxx.createPortal.weather.entity.WeatherImage; import com.xxxx.createPortal.weather.entity.WeatherInfo; import com.xxxx.createPortal.weather.service.IWeatherService; import com.xxxx.dhm.common.config.impl.PropertiesFactory; import com.xxxx.dhm.common.config.impl.XMLFactory; import com.xxxx.dhm.portalMS.common.Constants; import com.xxxx.dhm.portalMS.exception.PortalMSException; public class WeatherJob implements Job {     // 代表自动获取天气预报     private static final String AUTOMATIC = "0";     private IWeatherService weatherService;     public WeatherJob()     {         weatherService = (IWeatherService) ContextLoader.getCurrentWebApplicationContext().getBean("portalWeatherService");     }     private static final Logger logger = Logger.getLogger(WeatherJob.class);     /**      * 执行定时任务      */     public void execute(JobExecutionContext context)     {         String type = XMLFactory.getValueString("weather.type");         if (AUTOMATIC.equals(type))         {             logger.info("======================Begin WeatherTaskManager.execute()======================");             List<WeatherImage> imageList = new ArrayList<WeatherImage>();             DefaultHttpClient httpclient = new DefaultHttpClient();             String url = XMLFactory.getValueString("weather.weatherUrl");             HttpGet httpget = new HttpGet(url);             try             {                 HttpResponse response = httpclient.execute(httpget);                 httpentity entity = response.getEntity();                 if (entity != null)                 {                     WeatherInfo weather = new WeatherInfo();                     InputStream in = entity.getContent();                     int count = 0;                     while (count == 0)                     {                         count = Integer.parseInt("" + entity.getContentLength());                     }                     byte[] bytes = new byte[count];                     // 已经成功读取的字节的个数                     int readCount = 0;                     while (readCount <= count)                     {                         if (readCount == count)                             break;                         readCount += in.read(bytes,readCount,count - readCount);                     }                     // 转换成字符串                     String readContent = new String(bytes,"UTF-8");                     Document document = DocumentHelper.parseText(readContent);                     Element root = document.getRootElement();                     // 获取根节点下的子节点active                     Element data = root.element("data");                     // 天气信息                     String report = data.elementText("report");                     String weatherInfo[] = report.split(";");                     weather.setWeatherDesc(weatherInfo[0]);                   //weather.setTemperature(weatherInfo[1].replace( "气温",""));                     weather.setTemperature(weatherInfo[1].replace( ChineseCharacter.WEATHERJOB_TEMPERATURE,""));                     weather.setType(0);                     weather.setUpdater(1L);                     // 天气信息                     String dateStr = data.elementText("date");                     weather.setWeatherDate(dateStr);                     List<?> fieldList = root.selectNodes("/root/data/weathericons/icon");                     String suffix = Constants.SPLIT_DOT.getStringValue()                             + XMLFactory.getValueString("weather.imageSuffix");                     for (int i = 0; i < fieldList.size(); i++)                     {                         WeatherImage image = new WeatherImage();                         Element fieldEle = (Element) fieldList.get(i);                         image.setimage(fieldEle.getStringValue() + suffix);                         imageList.add(image);                     }                     weather.setWeatherImageList(imageList);                     try                     {                         weatherService.saveEntity(weather);                     }                     catch (PortalMSException e)                     {                         logger.error("insert the weather is Failed:",e);                     }                 }             }             catch (ClientProtocolException e1)             {                 logger.error("query the weather is Failed:",e1);             }             catch (IOException e1)             {                 logger.error("query the weather is Failed:",e1);             }             catch (Exception e1)             {                 logger.error("query the weather is Failed:",e1);             }             logger.info("======================WeatherTaskManager execute() Task End!======================");         }     }     public IWeatherService getWeatherService()     {         return weatherService;     }     public void setWeatherService(IWeatherService weatherService)     {         this.weatherService = weatherService;     } } 3、ContextLoader.getCurrentWebApplicationContext().getBean("portalWeatherService"); portalWeatherService类配置: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"     xmlns:aop="http://www.springframework.org/schema/aop"     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd     http://www.springframework.org/schema/tx     http://www.springframework.org/schema/tx/spring-tx-2.0.xsd     http://www.springframework.org/schema/aop     http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"     default-lazy-init="true">          <!-- ================================================================================================-->     <!-- =======================================action层配置=============================================-->     <!-- ================================================================================================-->         <bean id="WeatherAction" class="com.xxxxxx.dhm.portalMS.weather.action.WeatherAction" scope="prototype">         <property name="weatherService" ref="weatherService" />     </bean>          <bean id="PortalWeatherAction" class="com.xxxxxx.createPortal.weather.web.action.WeatherAction" scope="prototype">         <property name="weatherService" ref="portalWeatherService" />         <property name="localWeatherService" ref="weatherService" />     </bean>          <!-- ================================================================================================-->     <!-- =======================================service层配置=============================================-->     <!-- ================================================================================================-->         <bean id="weatherService" class="com.xxxxxx.dhm.portalMS.weather.service.impl.LocalWeatherServiceImpl">         <property name="weatherDao" ref="springWeatherDAO" />             <property name="genericDAO" ref="springWeatherDAO" />             </bean>              <bean id="portalWeatherService" class="com.xxxxxx.createPortal.weather.service.impl.WeatherServiceImpl">         <property name="weatherDao" ref="springPortalWeatherDAO" />             <property name="imageDao" ref="imageDao" />             <property name="genericDAO" ref="springPortalWeatherDAO" />             </bean>                  <!-- ================================================================================================-->     <!-- =======================================DAO层配置=================================================-->     <!-- ================================================================================================-->     <bean id="springWeatherDAO" class="com.xxxxxx.dhm.portalMS.weather.dao.impl.WeatherDaoImpl" parent="baseDao" />     <bean id="springPortalWeatherDAO" class="com.xxxxxx.createPortal.weather.dao.impl.WeatherDaoImpl" parent="baseDao" />     <bean id="imageDao" class="com.xxxxxx.createPortal.weather.dao.impl.WeatherImageDaoImpl" parent="baseDao" /> </beans> 4、XML文件配置信息:   <weather>     <!-- 0:自动 1:手动-->       <type>0</type>       <imagesPath>/images/weathericon/</imagesPath>       <imageSuffix>png</imageSuffix>       <weatherUrl>http://www.szmb.gov.cn/data_cache/szWeather/szweather.xml</weatherUrl>   </weather> 5、信息地址:   <weatherUrl>http://www.szmb.gov.cn/data_cache/szWeather/szweather.xml</weatherUrl> 该 XML 文件并未包含任何关联的样式信息。文档树显示如下。 <root><title>深圳市天气预报</title><link>http://www.szmb.gov.cn</link><pubDate>2013-12-10 11:03:00</pubDate><generator>深圳市气象局</generator><data><date>2013-12-10 11:00:00</date><report>多云,有轻度到中度灰霾;气温17-22℃;东北风2-3级;相对湿度35%-60% </report><timeframe>中午到傍晚</timeframe><maxt>22</maxt><mint>17</mint><aq>优</aq><ws>2-3</ws><wd>东北</wd><weathericons><icon>14</icon></weathericons><alarms><alarm><info>【深圳市灰霾预警】市气象台于10日09时55分在全市发布灰霾预警,预计今天白天到夜间我市能见度将降至3公里以下,尽量避免户外活动,并注意驾驶安全。</info><rdate>2013-12-10 09:55:00</rdate><ingnalNum>50331648</ingnalNum><area>全市陆地、西部海区、东部海区</area><type>灰霾</type><color/><icon>huimai</icon><pic>201312/29324.png</pic></alarm><alarm><info/><rdate>2013-12-10 09:55:00</rdate><ingnalNum>50331648</ingnalNum><area/><type>火险</type><color/><icon>huoxian</icon><pic>201312/29324.png</pic></alarm></alarms></data><conf><alarmiconpath>http://www.szmb.gov.cn/design/index/images/alarm_icon/icon_pinyin/</alarmiconpath><alarmpicpath>http://www.szmb.gov.cn/data_cache/szWeather/alarm/</alarmpicpath><weathericonpath>http://www.szmb.gov.cn/design/index/images/weather_icon2/</weathericonpath><alarmicontype>gif</alarmicontype><weathericontype>png</weathericontype></conf></root>   6、入库 public class WeatherDaoImpl extends IbatisDAO<WeatherInfo,Long> implements         IWeatherDao     public void saveEntity(final WeatherInfo info) throws PortalMSException     {         this.getsqlMapClientTemplate().execute(new sqlMapClientCallback()         {             public Object doInsqlMapClient(sqlMapExecutor executor)                     throws sqlException             {                 executor.startBatch();                 executor.insert("WeatherInfo.insert",info);                 if (null != info.getWeatherId())                 {                     if (info.getType().intValue() == 0)                     {                         executor.insert("WeatherInfo.insertnormal",info);                     }                     List<WeatherImage> weatherImageList = info                             .getWeatherImageList();                     if (weatherImageList != null && weatherImageList.size() > 0)                     {                         for (WeatherImage wImage : weatherImageList)                         {                             WeatherImage image = new WeatherImage();                             image.setWeatherId(info.getWeatherId());                             image.setimage(wImage.getimage());                             executor.insert("WeatherImage.insert",                                    image);                             if (info.getType().intValue() == 0)                             {                                 executor.insert("WeatherImage.insertimage",                                        image);                             }                         }                     }                 }                 return executor.executeBatch();             }         });     }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐