package com.sky.wechat.replyport;
import java.io.Writer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sky.wechat.replyport.model.Image;
import com.sky.wechat.replyport.model.News;
import com.sky.wechat.replyport.model.Text;
import com.sky.wechat.replyport.model.Tw;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
public class WechatMessageUtil {
private final static Log log = LogFactory.getLog(WechatMessageUtil.class);
/**将图文信息转换为xml
* @param n
* @return
*/
public static String news(News n) {
xstream.alias("xml", News.class);
xstream.alias("item", new Tw().getClass());
System.out.println(">>>>>>>>"+xstream.toXML(n));
return xstream.toXML(n);
}
/**将文本信息转化为xml
* @param t
* @return
*/
public static String text(Text t){
xstream.alias("xml", Text.class);
return xstream.toXML(t);
}
public static String image(Image i){
xstream.alias("xml", Image.class);
return xstream.toXML(i);
}
public static String getRelpay(Object o){
if(o==null){
return "";
}else{
if(o instanceof News){
return news((News)o);
}else if(o instanceof Text){
return text((Text)o);
}else if(o instanceof Image){
return image((Image)o);
}
}
return "";
}
private static XStream xstream = new XStream(new XppDriver() {
@Override
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings("unchecked")
public void startNode(String name, Class clazz) {
super.startNode(name);
}
@Override
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
}