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, 0, readCount, "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();
            }
        });
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值