首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

Atom/RSS feed 的应用 -2 WebSphere sMash 中对 feed 的支持

Atom/RSS feed 的应用 -2 WebSphere sMash 中对 feed 的支持

WebSphere sMash 中对 feed 的支持WebSphere sMash 作为 IBM 面向 Web2.0 应用程序提供的开发和运行平台,针对开发人员使用 feed 的不同场景提供了多种支持,主要目的是让使用基于 feed 的技术和协议变得更简易,避免针对协议细节的编程。在 sMash 中有多个组件为 feed 编程提供不同类型的支持,详见表 1。在简单的文字介绍之后,本文将提供多个简单场景的创建过程,展示 sMash 为 feed 编程带来的简单性和趣味性。
表 1. WebSphere sMash 中 feed 相关组件介绍模块名称用途zero.atom提供读取和输出 Atom 1.0 类型的 XML 文档的编程接口,包括将文档内容发布成为 feed 和一系列配置功能。zero.rss消费和发布 RSS 类型的 feed,得益于开放源代码项目 Rome 提供的扩展库,zero.rss 模块提供多种流行 RSS feed 间的格式转换功能。zero.feed提供服务器端和浏览器端操作 feed 内容的编程接口,包括 Java、Groovy 和 Ajax 风格的 API. zero.resource通过 Zero 资源模型提供一种高度简化的方式来创建 RESTful 资源,程序员可以通过该组件轻松发布基于 Atom 的开放编程接口。zero.assemble.flow通过 Assemble flow 调用第三方 REST 服务的功能,程序员可以轻松为各种 REST 服务提供者提供 feed 格式的数据视图。
为数据提供 feed 视图第一个例子介绍如何为已有的数据提供 feed 视图。这里用一个 MySQL 数据库代表数据源,有一张表 blog_posts 保存演示用的内容数据。Groovy 脚本将从中读取最新的 10 条记录,并为其提供 Atom 数据格式的 feed 视图。
1. 首先用 sMash 命令行工具创建应用程序 feedview.demo;
1
zero create feedview.demo




2. 在创建好的 sMash 应用程序的依赖管理配置文件 config/ivy.xml 中加入所需的模块。
清单 2. 使用 zero.atom 和 zero.data 模块,以及 MySQL 的 JDBC 驱动
1
2
3
4
5
6
<dependencies>      
        <dependency org="zero" name="zero.core" rev="[1.1.0.0, 2.0.0.0["/>
        <dependency org="zero" name="zero.atom" rev="[1.1.0.0, 2.0.0.0["/>
     <dependency org="zero" name="zero.data" rev="[1.1.0.0, 2.0.0.0["/>
     <dependency org="mysql" name="mysql-connector-java" rev="5.1+"/>
</dependencies>




3. 创建 Groovy 脚本并保存至 public/latest_posts/atom/index.groovy。
清单 3. 从数据库获取内容数据、创建 Atom 的数据结构,并将其发布成为一个 Atom feed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// file: /public/latest_posts/atom/index.groovy
try {
     // Get configured DataManager for data access
     def data = zero.data.groovy.Manager.create('blog_db')

     // Retrieve posts data
     def result = data.queryArray(
     'SELECT ID as id, post_date as updated, content as summary '
     + 'FROM blog_posts order by updated desc limit 0, 10')
     def feed = [
          title: "latest 10 posts",
          updated: new Date(),
          entries: result
     ]
     request.docType = 'feed'
     request.view = 'atom'
     request.atom.output = feed
     render()

} catch (Exception e) {
     request.status = HttpURLConnection.HTTP_INTERNAL_ERROR
     request.error.message = e.getMessage()
     request.view = "error"
     render()
}




4. 当然你还需要在配置文件 config/zero.config 中加入必要的信息来连接数据库。
清单 4. 连接 MySQL 数据库
1
2
3
4
5
6
7
8
/config/db/blog_db = {
         "class" : "com.mysql.jdbc.jdbc2.optional.MysqlDataSource",
         "serverName" : "localhost",
         "portNumber" : 3306,
         "databaseName" : "MYDBNAME",
         "user" : "someuser",
         "password" : "secretpasssword"
}




5. 在命令行中输入如下命令来解析、获取相关的模块,并启动这个 sMash 应用程序:
1
2
zero resolve
zero start




6. 使用浏览器访问 http://localhost:8080/latest_posts/atom/,你将会看到已经发布为 Atom feed 的数据。
返回列表