练手小程序——无第三方依赖解析RSS

实现抓取RSS信息并简单解析后显示。提供搜索功能,可只显示相应关键字的RSS Items。无第三方jar包依赖。

package com.ojdbc;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Shengxinya on 2016/6/1.
 */
public class RSSSearcher extends JFrame {

    private final Map<String, List<String>> rssResMap = new HashMap<>();
    private final String searching = "正在抓取中……";
    private final String noRes = "无结果……";
    private JLabel urlLabel = new JLabel();
    private JTextField urlTF = new JTextField();
    private JLabel strLabel = new JLabel();
    private JTextField strTF = new JTextField();
    private JButton searchBn = new JButton();
    private JTextArea resTA = new JTextArea();


    /**
     * 解析URL对应的Rss中的items并放入对应Map中
     *
     * @param urlPath url路径
     */
    public void rssParser(String urlPath) throws IOException, ParserConfigurationException, SAXException {
        URL url = null;

        url = new URL(urlPath);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        Document doc = null;
        List<String> list = new ArrayList<>(50);

        builder = dbf.newDocumentBuilder();
        doc = builder.parse(url.openStream());
        NodeList nList = doc.getElementsByTagName("item");
        for (int i = 0, j = nList.getLength(); i < j; i++) {
            list.add(nList.item(i).getTextContent());
        }

        rssResMap.put(urlPath, list);
    }

    /**
     * 初始化界面
     */
    public void init() {
        this.setSize(800, 600);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new FlowLayout());
        this.setTitle("RssSearcher");
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        urlLabel.setText("URL:");
        urlLabel.setSize(30, 40);
        this.add(urlLabel);
        urlTF.setColumns(30);
        this.add(urlTF);
        strLabel.setText("关键词:");
        strLabel.setSize(30, 40);
        this.add(strLabel);
        strTF.setColumns(25);
        this.add(strTF);
        searchBn.setText("Search");
        searchBn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                doSearch();
            }
        });
        this.add(searchBn);
        resTA.setColumns(65);
        resTA.setEnabled(false);
        resTA.setRows(30);
        resTA.setAutoscrolls(true);
        resTA.setLineWrap(true);
        resTA.setWrapStyleWord(true);

        JScrollPane scroll = new JScrollPane(resTA);
        scroll.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        this.add(scroll);
        this.setVisible(true);
    }

    /**
     * Search处理方法
     */
    public void doSearch() {
        if (isEmpty(urlTF.getText())) {
            return;
        }
        searchBn.setEnabled(false);
        String str = strTF.getText();
        CountDownLatch fcdl = new CountDownLatch(1);
        new Thread() {
            public void run() {
                resTA.setText(searching);
                //同一url不用再次请求
                if (!rssResMap.containsKey(urlTF.getText())) {
                    try {
                        rssParser(urlTF.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                        fcdl.countDown();
                        return;
                    }
                }
                List<String> list = rssResMap.get(urlTF.getText());
                if (list == null || list.size() == 0) {
                    return;
                }
                resTA.setText("");
                for (String itemText : list) {
                    if (isEmpty(strTF.getText()) || itemText.contains(str)) {
                        resTA.setText(resTA.getText() + itemText);
                    }

                }
                fcdl.countDown();
            }
        }.start();
        try {
            fcdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (isEmpty(resTA.getText()) || resTA.getText().equals(searching)) {
            resTA.setText(noRes);
        }
        searchBn.setEnabled(true);
    }

    /**
     * 判断给定字符串是否为空
     *
     * @param str 给定字符串
     * @return 是否为空
     */
    public boolean isEmpty(String str) {
        return str == null || "".equals(str);
    }

    public static void main(String[] args) {
        RSSSearcher searcher = new RSSSearcher();
        searcher.init();
    }
}

 

 

此条目发表在技术, 未分类分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。