rss 开发实例 1 AbstractFeedServlet

package com.ouou.webapp.rss;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;
import com.ouou.webapp.servlet.AbstractLeyuanServlet;
import com.ouou.video.om.Videos;
import com.ouou.video.om.Category;
import com.ouou.video.om.Tags;
import com.ouou.util.VideoUtils;
import com.ouou.util.DomainUtil;
import com.ouou.util.ImagesUtil;
import com.ouou.util.DateUtil;
import com.ouou.schedule.ScheduleManager;
import com.leyuan.client.model.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.RequestUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.context.ApplicationContext;
import org.jdom.CDATA;
import org.jdom.Verifier;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
­
/**
* Created by IntelliJ IDEA.
* User: xingtao
* Date: 2006-9-11
* Time: 18:55:35
* To change this template use File | Settings | File Templates.
*/
public abstract class AbstractFeedServlet extends AbstractLeyuanServlet {
    private static final Log logger = LogFactory.getLog(AbstractFeedServlet.class);
    private static final String MIME_TYPE = "application/xml; charset=UTF-8";
    private static final String CONTENT_TYPE = "text/plain";
    private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
    protected static final String LANGUAGE = "zh-cn";
    protected static final String ENCODING = "UTF-8";
    protected ApplicationContext context;
    protected Properties copy_prop;
    protected ScheduleManager scheduleMgr;
    public void init() {
        try {
            super.init();
        } catch (ServletException e) {
            logger.error(e);
        }
        context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        copy_prop = (Properties) context.getBean("copyright");
        scheduleMgr = (ScheduleManager) context.getBean("scheduleManager");
    }
    public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        try {
            String rss = RequestUtils.getStringParameter(request,"rss","rss_2.0");
            if(!"rss_2.0".equalsIgnoreCase(rss)&&!"atom_0.3".equalsIgnoreCase(rss)){
               rss = "rss_2.0";
            }
            String type = RequestUtils.getStringParameter(request,"type","recommemd");
            SyndFeed feed = getFeed(request,type);
            if(null==feed){
                showResult(response,FAIL,"未知的类型");
            }else{
                feed.setFeedType(rss);
                response.setContentType(MIME_TYPE);
                SyndFeedOutput output = new SyndFeedOutput();
                output.output(feed, response.getWriter());
            }
        } catch (FeedException ex) {
            String msg = COULD_NOT_GENERATE_FEED_ERROR;
            logger.error(ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        }
    }
    public SyndFeed getBaseFeed(){
        SyndFeed feed = new SyndFeedImpl();
        feed.setEncoding(ENCODING);
        feed.setLanguage(LANGUAGE);
        feed.setPublishedDate(Calendar.getInstance().getTime());
        feed.setCopyright(copy_prop.getProperty("copyright"));
        return feed;
    }
    public abstract SyndFeed getFeed(HttpServletRequest request,String type)
        throws IOException, FeedException;
    protected SyndFeed process(SyndFeed feed, List list){
       List entryList = new ArrayList();
       Properties prop = (Properties) context.getBean("video");
       String info = prop.getProperty("info");
       for(Videos videos:list){
            try{
                User user = umanager.getUserById(videos.getUserId());
                Category category = cmanager.getCateory(videos.getCateId());
                SyndEntry entry = new SyndEntryImpl();
                SyndContent description = new SyndContentImpl();
                entry.setTitle(replaceLegalXmlCcharacter(videos.getName()));
                String code = VideoUtils.genPlayCode(videos.getVideoId(),
                        videos.getCateId(), videos.getUserId(), 1000);
                String video_url = new StringBuffer(DomainUtil.getDefaultDomain()).append("/play/v_").append(code).append(".html").toString();
                String image_url = ImagesUtil.getDefaultCoverUrl(videos.getCoverUrl());
                String space_url = new StringBuffer(DomainUtil.getSpaceDomain()).append("/space/index/").append(user.getUserName()).toString();
                String category_url = new StringBuffer(DomainUtil.getDefaultDomain()).append("/category_disp/").append(videos.getCateId()).toString();
                List tags = tmanager.getTags(videos.getVideoId());
                StringBuffer buffer = new StringBuffer();
                for(Tags tag:tags){
                    try{
                        buffer.append(""+tag.getName()+"");
                    }catch(Exception e){
                        logger.error(e);
                    }
                }
                entry.setLink(video_url);
                entry.setAuthor(replaceLegalXmlCcharacter(user.getUserName()));
                entry.setPublishedDate(new Date(videos.getCreateTime().getTime()+8*60*60*1000));
­
                description.setType(CONTENT_TYPE);
                String desc = info.replaceAll("#video_url",video_url);
                desc = desc.replaceAll("#image",image_url);
                desc = desc.replaceAll("#name",videos.getName());
                desc = desc.replaceAll("#space_url",space_url);
                desc = desc.replaceAll("#auther",user.getUserName());
                desc = desc.replaceAll("#category_url",category_url);
                desc = desc.replaceAll("#category_name",category.getName());
                desc = desc.replaceAll("#create_time",SHORT_SDF.format(videos.getCreateTime()));
                desc = desc.replaceAll("#total_time", DateUtil.totalTimeString(videos.getTotalTime()));
                desc = desc.replaceAll("#star",String.valueOf(videos.getStar()));
                desc = desc.replaceAll("#clicks",String.valueOf(videos.getClicks()));
                desc = desc.replaceAll("#comments",String.valueOf(videos.getComments()));
                desc = desc.replaceAll("#favorites",String.valueOf(videos.getFavorites()));
                desc = desc.replaceAll("#vote_num",String.valueOf(videos.getVoteNum()));
                desc = desc.replaceAll("#desc",videos.getDescription());
                desc = desc.replaceAll("#tag",buffer.toString());
                description.setValue(replaceLegalXmlCcharacter(desc));
                entry.setDescription(description);
                entryList.add(entry);
            }catch(Exception e){
                //logger.error(e);                
            }
        }        
        feed.setEntries(entryList);
        return feed;
    }
    public static String replaceLegalXmlCcharacter(String xml){
        String newXml = xml;
        for(int i = 0; i < xml.length(); i++){
            char ch = xml.charAt(i);
            if(!isChar(ch)){
                 //newXml = newXml.substring(0, i) + " " + newXml.substring(i+1);
                newXml = xml.replace(ch,' ');
            }            
        }
        return newXml;
    }
    public static boolean isChar(int c){
        
        if (c == '/n') return true;
        if (c == '/r') return true;
        if (c == '/t') return true;
        
        if (c < 0x20) return false;  if (c <= 0xD7FF) return true;
        if (c < 0xE000) return false;  if (c <= 0xFFFD) return true;
        if (c < 0x10000) return false;  if (c <= 0x10FFFF) return true;
        
        return false;
    }
}
 

你可能感兴趣的:(编程体会)