08-04
15
JAVA与WEB2.0亲密接触
作者:Java伴侣 日期:2008-04-15
现在越来越多的网站应用都加入RSS或是ATOM这一类新功能,用户可以通过它更准确的订阅到自己想知道的信息,去掉大量的陈旧信息和无用的广告,信息比以往任何时候都要来得及时。而作为公司来说,统一的接口会使市场更加的规范,使得个人用户的选择更多,我们可以利用RSS来轻松的从一个BLOG搬家到另一个BLOG。这也让我们看到了,WEB2.0这一理念越来越被广泛应用。
由于开源产业的不规范性,出现了RSS与ATOM两类格式的XML文本。虽然newsfeed这种新型的新闻供应机制存在种种质疑,但newsfeed的潜力是有目共睹,势不可挡。不管在将来谁会取代谁,作为我们程序员来说也应尽快尽可能全面的了解此类新技术。而国内JSP方面对于此技术的关注实在少得可怜。资料也甚是难找。
下面本站将介绍用JAVA如何来生成RSS&ATOM.XML
这里我们用到了SUN公司开发的ROME.jar做这一系列事情。
先制作一个接口类及其抽象方法
接着我们做一个缓存来存放XML,便于以后在update()执行时候作为对照,如果新闻没有更新,将首先读取缓存。
再做一个生成newsfeed类
到了这部,就可以用过键盘来输入其三个属性作为控制了。
属性介绍:
下面我们还可以结合servlet在WEB应用上生成XML
}
由于开源产业的不规范性,出现了RSS与ATOM两类格式的XML文本。虽然newsfeed这种新型的新闻供应机制存在种种质疑,但newsfeed的潜力是有目共睹,势不可挡。不管在将来谁会取代谁,作为我们程序员来说也应尽快尽可能全面的了解此类新技术。而国内JSP方面对于此技术的关注实在少得可怜。资料也甚是难找。
下面本站将介绍用JAVA如何来生成RSS&ATOM.XML
这里我们用到了SUN公司开发的ROME.jar做这一系列事情。
先制作一个接口类及其抽象方法
复制内容到剪贴板 程序代码
import java.util.Collection;
import java.util.Date;
/**
* 接口
* @author blurxx
*/
public interface Depot {
public abstract Collection getFiles();
public abstract Date getLastUpdateDate();
public abstract void update();
}
import java.util.Date;
/**
* 接口
* @author blurxx
*/
public interface Depot {
public abstract Collection getFiles();
public abstract Date getLastUpdateDate();
public abstract void update();
}
接着我们做一个缓存来存放XML,便于以后在update()执行时候作为对照,如果新闻没有更新,将首先读取缓存。
复制内容到剪贴板 程序代码
/**
* Depot of files avialable in reverse chronological order.
* @author Dave Johnson
*/
public class FileDepot implements Depot {
private String path;
private ArrayList files = new ArrayList();
private Date lastModified = null;
/** Create file depot in existing directory */
public FileDepot(String path) {
this.path = path;
update();
}
public synchronized void update()
{
File depotDir = new File(path);
String[] fileNames = depotDir.list();
for (int i = 0; i < fileNames.length; i++) {
File file = new File(depotDir.getPath() + File.separator + fileNames[i]);
files.add(file);
Date fileLastModified = new Date(file.lastModified());
if (lastModified == null || lastModified.compareTo(fileLastModified) < 0) {
lastModified = fileLastModified;
}
}
Collections.sort(files, new FileComparator());
}
/** Get files sorted in reverse chronological order */
public synchronized Collection getFiles() {
return files;
}
public synchronized Date getLastUpdateDate() {
return lastModified;
}
/** Helps to sort files in reverse chrono order */
class FileComparator implements Comparator {
public int compare(Object o1, Object o2) {
File file1 = (File)o1;
File file2 = (File)o2;
if (file1.lastModified() == file2.lastModified()) return 0;
else if (file1.lastModified() < file2.lastModified()) return 1;
else return -1;
}
}
}
* Depot of files avialable in reverse chronological order.
* @author Dave Johnson
*/
public class FileDepot implements Depot {
private String path;
private ArrayList files = new ArrayList();
private Date lastModified = null;
/** Create file depot in existing directory */
public FileDepot(String path) {
this.path = path;
update();
}
public synchronized void update()
{
File depotDir = new File(path);
String[] fileNames = depotDir.list();
for (int i = 0; i < fileNames.length; i++) {
File file = new File(depotDir.getPath() + File.separator + fileNames[i]);
files.add(file);
Date fileLastModified = new Date(file.lastModified());
if (lastModified == null || lastModified.compareTo(fileLastModified) < 0) {
lastModified = fileLastModified;
}
}
Collections.sort(files, new FileComparator());
}
/** Get files sorted in reverse chronological order */
public synchronized Collection getFiles() {
return files;
}
public synchronized Date getLastUpdateDate() {
return lastModified;
}
/** Helps to sort files in reverse chrono order */
class FileComparator implements Comparator {
public int compare(Object o1, Object o2) {
File file1 = (File)o1;
File file2 = (File)o2;
if (file1.lastModified() == file2.lastModified()) return 0;
else if (file1.lastModified() < file2.lastModified()) return 1;
else return -1;
}
}
}
再做一个生成newsfeed类
复制内容到剪贴板 程序代码
import java.io.*;
import java.util.*;
import com.sun.syndication.feed.WireFeed;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.WireFeedOutput;
/**
* 使用Java生成newsfeed
* @author blurxx
*
*/
public class DepotNewsfeedWriter {
private static final List Collections = null;
private Depot depot;
public DepotNewsfeedWriter(Depot depot) {
this.depot = depot;
}
public void write(Writer writer, String baseURL, String format)
throws Exception {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType(format);
feed.setLanguage("en-us");
feed.setTitle("File Depot Newsfeed");
feed.setDescription("Newly uploaded files in the File Depot");
feed.setLink(baseURL);
feed.setUri(baseURL + "/depot-newsfeed");
feed.setPublishedDate(depot.getLastUpdateDate());
SyndLink selfLink = new SyndLinkImpl();
selfLink.setHref(feed.getUri());
selfLink.setRel("self");
feed.setLinks(Collections); //
ArrayList<SyndEntry> entries = new ArrayList<SyndEntry>();
Iterator files = depot.getFiles().iterator();
while (files.hasNext()) {
File file = (File) files.next();
SyndEntry entry = new SyndEntryImpl();
String url = baseURL + file.getName();
entry.setLink(url);
entry.setUri(url);
entry.setTitle(file.getName());
entry.setPublishedDate(new Date(file.lastModified())); // 索取文件最后一次修改时间
entry.setUpdatedDate(new Date(file.lastModified()));
SyndContent description = new SyndContentImpl();
description.setValue("Click <a href='" + url + "'>"
+ file.getName() + "</a>to download the file.");
entry.setDescription(description);
entries.add(entry);// 包含多个entry
}
feed.setEntries(entries);
WireFeedOutput output = new WireFeedOutput();
WireFeed wireFeed = feed.createWireFeed();
output.output(wireFeed, writer);
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if (args.length < 3) {
System.out.println("USER:DepotNewsfeedWriter "
+ "[depotDir] [depotUrl] [file] [format]");
return;
}
String depotDir = args[0];
Depot depot = new FileDepot(depotDir);
DepotNewsfeedWriter newsfeedWriter = new DepotNewsfeedWriter(depot);
new DepotNewsfeedWriter(depot); // |#11
String depotUrl = args[1]; // 输入1
String filePath = args[2]; // 输入2
String format = args[3]; // 输入3
FileWriter writer = new FileWriter(filePath);
newsfeedWriter.write(writer, depotUrl, format);
}
}
import java.util.*;
import com.sun.syndication.feed.WireFeed;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.WireFeedOutput;
/**
* 使用Java生成newsfeed
* @author blurxx
*
*/
public class DepotNewsfeedWriter {
private static final List Collections = null;
private Depot depot;
public DepotNewsfeedWriter(Depot depot) {
this.depot = depot;
}
public void write(Writer writer, String baseURL, String format)
throws Exception {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType(format);
feed.setLanguage("en-us");
feed.setTitle("File Depot Newsfeed");
feed.setDescription("Newly uploaded files in the File Depot");
feed.setLink(baseURL);
feed.setUri(baseURL + "/depot-newsfeed");
feed.setPublishedDate(depot.getLastUpdateDate());
SyndLink selfLink = new SyndLinkImpl();
selfLink.setHref(feed.getUri());
selfLink.setRel("self");
feed.setLinks(Collections); //
ArrayList<SyndEntry> entries = new ArrayList<SyndEntry>();
Iterator files = depot.getFiles().iterator();
while (files.hasNext()) {
File file = (File) files.next();
SyndEntry entry = new SyndEntryImpl();
String url = baseURL + file.getName();
entry.setLink(url);
entry.setUri(url);
entry.setTitle(file.getName());
entry.setPublishedDate(new Date(file.lastModified())); // 索取文件最后一次修改时间
entry.setUpdatedDate(new Date(file.lastModified()));
SyndContent description = new SyndContentImpl();
description.setValue("Click <a href='" + url + "'>"
+ file.getName() + "</a>to download the file.");
entry.setDescription(description);
entries.add(entry);// 包含多个entry
}
feed.setEntries(entries);
WireFeedOutput output = new WireFeedOutput();
WireFeed wireFeed = feed.createWireFeed();
output.output(wireFeed, writer);
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if (args.length < 3) {
System.out.println("USER:DepotNewsfeedWriter "
+ "[depotDir] [depotUrl] [file] [format]");
return;
}
String depotDir = args[0];
Depot depot = new FileDepot(depotDir);
DepotNewsfeedWriter newsfeedWriter = new DepotNewsfeedWriter(depot);
new DepotNewsfeedWriter(depot); // |#11
String depotUrl = args[1]; // 输入1
String filePath = args[2]; // 输入2
String format = args[3]; // 输入3
FileWriter writer = new FileWriter(filePath);
newsfeedWriter.write(writer, depotUrl, format);
}
}
到了这部,就可以用过键盘来输入其三个属性作为控制了。
属性介绍:
引用内容
depotDir:文件库文件存放目录的全路径,在这个应用中,我们需要在根目录下建议一个depot文件夹
depotUrl:文件库在Web上的URL
file:要生成的newsfeed文件名
format:生成的newsfeed格式,比如说:rss_0.91、rss_1.0、rss2.0或者是atom_1.0
depotUrl:文件库在Web上的URL
file:要生成的newsfeed文件名
format:生成的newsfeed格式,比如说:rss_0.91、rss_1.0、rss2.0或者是atom_1.0
下面我们还可以结合servlet在WEB应用上生成XML
复制内容到剪贴板 程序代码
package com.manning.blogapps.chapter08.filedpot;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DepotNewsfeedServlet extends HttpServlet {
private static final long serialVersionUID = 182023042307203449L;
/**
* Constructor of the object.
*/
public DepotNewsfeedServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext application = this.getServletContext();
Depot depot = (Depot) application.getAttribute("depot");
if(depot == null){
depot = new FileDepot(request.getRealPath("/depot"));
application.setAttribute("depot", depot);
}
try{
String format = request.getParameter("format");
if(format ==null)
format ="rss_2.0";
if(format.startsWith("rss")){
response.setContentType("application/rss+xml;charset=utf-8");
}else{
response.setContentType("application/atom+xml;charset=utf-8");
}
String depotUrl = request.getRequestURI().toString();
//String depotUrl = url.substring(0,url.lastIndexOf("/"));
depotUrl = "http://"+request.getRemoteHost()+depotUrl;
DepotNewsfeedWriter depotWriter = new DepotNewsfeedWriter(depot);
depotWriter.write(response.getWriter(), depotUrl, format);
}
catch(Exception ex){
String msg ="ERROR:generating newsfeed";
log(msg,ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,msg);
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DepotNewsfeedServlet extends HttpServlet {
private static final long serialVersionUID = 182023042307203449L;
/**
* Constructor of the object.
*/
public DepotNewsfeedServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext application = this.getServletContext();
Depot depot = (Depot) application.getAttribute("depot");
if(depot == null){
depot = new FileDepot(request.getRealPath("/depot"));
application.setAttribute("depot", depot);
}
try{
String format = request.getParameter("format");
if(format ==null)
format ="rss_2.0";
if(format.startsWith("rss")){
response.setContentType("application/rss+xml;charset=utf-8");
}else{
response.setContentType("application/atom+xml;charset=utf-8");
}
String depotUrl = request.getRequestURI().toString();
//String depotUrl = url.substring(0,url.lastIndexOf("/"));
depotUrl = "http://"+request.getRemoteHost()+depotUrl;
DepotNewsfeedWriter depotWriter = new DepotNewsfeedWriter(depot);
depotWriter.write(response.getWriter(), depotUrl, format);
}
catch(Exception ex){
String msg ="ERROR:generating newsfeed";
log(msg,ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,msg);
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
评论: 0 | 引用: 0 | 查看次数: 551
发表评论