public class WeatherTextHandler extends DefaultMessageHandler {
@Override
public boolean canDo(Map<String, String> requestMap) {
String content = requestMap.get("Content").trim();
String msgType = requestMap.get("MsgType");
return MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgType) && content.startsWith("天气");
}
@Override
public BaseMessage handleByMe(Map<String, String> requestMap) {
String city = requestMap.get("Content").trim();
String[] strings = city.split("@");
if ("天气".equals(city)) {//天气
return MessageFactory.createTextMessage(fromUserName, toUserName, ContentUtil.getWeatherUsage());
}else if(strings.length==3){//天气@@盘锦
String message = BaiduWeatherService.getTodayInfo(strings[2]);
return MessageFactory.createTextMessage(fromUserName, toUserName, message);
}else {//天气@盘锦
List<Article> articles = BaiduWeatherService.getFutureInfo(strings[1]);
return MessageFactory.createNewsMessage(fromUserName, toUserName, articles );
}
}
@Test
public void testHandleMessage(){
Map<String, String> requestMap = new HashMap<String, String>();
requestMap.put("FromUserName", "dfgsd");
requestMap.put("ToUserName", "dfsfd");
requestMap.put("MsgType", MessageUtil.REQ_MESSAGE_TYPE_TEXT);
requestMap.put("Content", "天气@@盘锦");
BaseMessage message = new WeatherTextHandler().handleMessage(requestMap);
System.out.println(MessageUtil.messageToXml(message));
}
@Test
public void testSplit(){
String[] strings = "天气@@盘锦".split("@");
System.out.println(strings.length);
System.out.println(strings[2]);
}
}
public static String getWeatherUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("天气操作指南").append("\n\n");
buffer.append("回复:天气@城市名 返回未来几天的").append("\n");
buffer.append("回复:天气@@城市名 返回今天的详细天气").append("\n\n");
buffer.append("回复“?/?”显示主菜单");
return buffer.toString();
}
/**
* 百度天气查询,可以查询最近几天的,也可以查询今天的然后给出建议
* @author 熊诗言
*
*/
public class BaiduWeatherService {
private static String getXmlCode(String city) throws UnsupportedEncodingException{
String requestUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+city+"&output=xml&ak=4Dlcr5PebDTnRuIsv6kChkA5";
StringBuffer buffer = null;
try {
// 建立连接
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
// 获取输入流
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// 读取返回结果
buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
httpUrlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString(); //返回获取的xml字符串
}
//获取天气信息
private static Element getXMLRoot(String city) {
try {
String xml= getXmlCode(URLEncoder.encode(city, "utf-8")); //设置输入城市
Document doc = null;
String info = null;
// 读取并解析XML文档
//下面的是通过解析xml字符串的
doc = DocumentHelper.parseText(xml); // 将字符串转为XML
Element rootElt = doc.getRootElement(); // 获取根节点
String status=rootElt.elementText("status"); //获取状态,如果等于success,表示有数据
if(!"success".equals(status))
return null; //如果不存在数据,直接返回
return rootElt;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
public static String getTodayInfo(String city) {
Element rootElt = getXMLRoot(city);
StringBuffer buffer = new StringBuffer();
buffer.append("今天的建议").append("\n");
try {
Iterator iter = rootElt.elementIterator("results"); // 获取根节点下的子节点results
List<Element> listTitle=null; //项目
List<Element> listDes=null; //项目描述
//遍历results节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
Iterator iters = recordEle.elementIterator("index"); //
//遍历results节点下的index节点
while (iters.hasNext()) {
Element itemEle = (Element) iters.next();
listTitle=itemEle.elements("title");
listDes=itemEle.elements("des");
}
for(int i=0;i<listTitle.size();i++){ //由于每一个list.size都相等,这里统一处理
Element title=(Element)listTitle.get(i); //依次取出date
Element des=(Element)listDes.get(i);//..
buffer.append(title.getText()).append(":").append(des.getText())
.append("\n");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
@SuppressWarnings("unchecked")
public static List<Article> getFutureInfo(String city) {
Element rootElt = getXMLRoot(city);
Document doc = null;
List<Article> articles = new ArrayList<Article>();
try {
Iterator iter = rootElt.elementIterator("results"); // 获取根节点下的子节点results
List<Element> listdate=null; //用来存放日期
List<Element> listday=null; //用来存放白天图片路径信息
List<Element> listweather=null;//天气
List<Element> listtem=null;//温度
//遍历results节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
Iterator iters = recordEle.elementIterator("weather_data"); //
//遍历results节点下的weather_data节点
while (iters.hasNext()) {
Element itemEle = (Element) iters.next();
listdate=itemEle.elements("date");
//将date集合放到listdate中
listday=itemEle.elements("dayPictureUrl");
listweather=itemEle.elements("weather");
listtem=itemEle.elements("temperature");
}
for(int i=0;i<listdate.size();i++){ //由于每一个list.size都相等,这里统一处理
Element eledate=(Element)listdate.get(i); //依次取出date
Element eleday=(Element)listday.get(i);//..
Element eleweather=(Element)listweather.get(i);
Element eletem=(Element)listtem.get(i);
/* buff.append(eledate.getText()+
"==="+eleweather.getText()+
"==="+eletem.getText()+
"==="+eleday.getText()+"\n"); //拼接信息
*/
/*buffer.append("[").append().append("][").append(eleweather.getText())
.append("][").append(eletem.getText()).append("]["+"<img src=\"")
.append(eleday.getText()).append("\">"+"]\n");*/
Article article = new Article();
article.setTitle(eledate.getText()+":"+eleweather.getText()+":"+eletem.getText());
article.setDescription(eleweather.getText()+":"+eletem.getText());
article.setPicUrl(eleday.getText());
article.setUrl(eleday.getText());
articles.add(article);
//http://saebbs.com/forum.php?mod=viewthread&tid=23873&highlight=%E5%A4%A9%E6%B0%94
//http://saebbs.com/forum.php?mod=viewthread&tid=23455&extra=page%3D10
}
}
} catch (Exception e) {
e.printStackTrace();
}
return articles;
}
public static void main(String[] args){
//测试
System.out.println(getTodayInfo("盘锦"));
}
}
@Override
public boolean canDo(Map<String, String> requestMap) {
String content = requestMap.get("Content").trim();
String msgType = requestMap.get("MsgType");
return MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgType) && content.startsWith("天气");
}
@Override
public BaseMessage handleByMe(Map<String, String> requestMap) {
String city = requestMap.get("Content").trim();
String[] strings = city.split("@");
if ("天气".equals(city)) {//天气
return MessageFactory.createTextMessage(fromUserName, toUserName, ContentUtil.getWeatherUsage());
}else if(strings.length==3){//天气@@盘锦
String message = BaiduWeatherService.getTodayInfo(strings[2]);
return MessageFactory.createTextMessage(fromUserName, toUserName, message);
}else {//天气@盘锦
List<Article> articles = BaiduWeatherService.getFutureInfo(strings[1]);
return MessageFactory.createNewsMessage(fromUserName, toUserName, articles );
}
}
@Test
public void testHandleMessage(){
Map<String, String> requestMap = new HashMap<String, String>();
requestMap.put("FromUserName", "dfgsd");
requestMap.put("ToUserName", "dfsfd");
requestMap.put("MsgType", MessageUtil.REQ_MESSAGE_TYPE_TEXT);
requestMap.put("Content", "天气@@盘锦");
BaseMessage message = new WeatherTextHandler().handleMessage(requestMap);
System.out.println(MessageUtil.messageToXml(message));
}
@Test
public void testSplit(){
String[] strings = "天气@@盘锦".split("@");
System.out.println(strings.length);
System.out.println(strings[2]);
}
}
public static String getWeatherUsage() {
StringBuffer buffer = new StringBuffer();
buffer.append("天气操作指南").append("\n\n");
buffer.append("回复:天气@城市名 返回未来几天的").append("\n");
buffer.append("回复:天气@@城市名 返回今天的详细天气").append("\n\n");
buffer.append("回复“?/?”显示主菜单");
return buffer.toString();
}
/**
* 百度天气查询,可以查询最近几天的,也可以查询今天的然后给出建议
* @author 熊诗言
*
*/
public class BaiduWeatherService {
private static String getXmlCode(String city) throws UnsupportedEncodingException{
String requestUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+city+"&output=xml&ak=4Dlcr5PebDTnRuIsv6kChkA5";
StringBuffer buffer = null;
try {
// 建立连接
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
// 获取输入流
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// 读取返回结果
buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
httpUrlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString(); //返回获取的xml字符串
}
//获取天气信息
private static Element getXMLRoot(String city) {
try {
String xml= getXmlCode(URLEncoder.encode(city, "utf-8")); //设置输入城市
Document doc = null;
String info = null;
// 读取并解析XML文档
//下面的是通过解析xml字符串的
doc = DocumentHelper.parseText(xml); // 将字符串转为XML
Element rootElt = doc.getRootElement(); // 获取根节点
String status=rootElt.elementText("status"); //获取状态,如果等于success,表示有数据
if(!"success".equals(status))
return null; //如果不存在数据,直接返回
return rootElt;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
public static String getTodayInfo(String city) {
Element rootElt = getXMLRoot(city);
StringBuffer buffer = new StringBuffer();
buffer.append("今天的建议").append("\n");
try {
Iterator iter = rootElt.elementIterator("results"); // 获取根节点下的子节点results
List<Element> listTitle=null; //项目
List<Element> listDes=null; //项目描述
//遍历results节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
Iterator iters = recordEle.elementIterator("index"); //
//遍历results节点下的index节点
while (iters.hasNext()) {
Element itemEle = (Element) iters.next();
listTitle=itemEle.elements("title");
listDes=itemEle.elements("des");
}
for(int i=0;i<listTitle.size();i++){ //由于每一个list.size都相等,这里统一处理
Element title=(Element)listTitle.get(i); //依次取出date
Element des=(Element)listDes.get(i);//..
buffer.append(title.getText()).append(":").append(des.getText())
.append("\n");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
@SuppressWarnings("unchecked")
public static List<Article> getFutureInfo(String city) {
Element rootElt = getXMLRoot(city);
Document doc = null;
List<Article> articles = new ArrayList<Article>();
try {
Iterator iter = rootElt.elementIterator("results"); // 获取根节点下的子节点results
List<Element> listdate=null; //用来存放日期
List<Element> listday=null; //用来存放白天图片路径信息
List<Element> listweather=null;//天气
List<Element> listtem=null;//温度
//遍历results节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
Iterator iters = recordEle.elementIterator("weather_data"); //
//遍历results节点下的weather_data节点
while (iters.hasNext()) {
Element itemEle = (Element) iters.next();
listdate=itemEle.elements("date");
//将date集合放到listdate中
listday=itemEle.elements("dayPictureUrl");
listweather=itemEle.elements("weather");
listtem=itemEle.elements("temperature");
}
for(int i=0;i<listdate.size();i++){ //由于每一个list.size都相等,这里统一处理
Element eledate=(Element)listdate.get(i); //依次取出date
Element eleday=(Element)listday.get(i);//..
Element eleweather=(Element)listweather.get(i);
Element eletem=(Element)listtem.get(i);
/* buff.append(eledate.getText()+
"==="+eleweather.getText()+
"==="+eletem.getText()+
"==="+eleday.getText()+"\n"); //拼接信息
*/
/*buffer.append("[").append().append("][").append(eleweather.getText())
.append("][").append(eletem.getText()).append("]["+"<img src=\"")
.append(eleday.getText()).append("\">"+"]\n");*/
Article article = new Article();
article.setTitle(eledate.getText()+":"+eleweather.getText()+":"+eletem.getText());
article.setDescription(eleweather.getText()+":"+eletem.getText());
article.setPicUrl(eleday.getText());
article.setUrl(eleday.getText());
articles.add(article);
//http://saebbs.com/forum.php?mod=viewthread&tid=23873&highlight=%E5%A4%A9%E6%B0%94
//http://saebbs.com/forum.php?mod=viewthread&tid=23455&extra=page%3D10
}
}
} catch (Exception e) {
e.printStackTrace();
}
return articles;
}
public static void main(String[] args){
//测试
System.out.println(getTodayInfo("盘锦"));
}
}