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

Atom/RSS feed 的应用 -5 为第三方服务提供 feed 数据视图

Atom/RSS feed 的应用 -5 为第三方服务提供 feed 数据视图

为第三方服务提供 feed 数据视图虽然 feed 已经成为 Web 2.0 流行风潮中数据服务最常见的发布格式,但现实 Web2.0 世界仍旧存在大量数据服务并没有使用 RSS 或 Atom 等格式,如 Amazon Web Services,Ebay Web Services 等提供的 HTTP API。使用 WebSphere sMash 可以连接这类数据服务,并且提供将 XML 格式的数据转换成 feed 格式。
这里以 Last.fm 提供的 Track Search 服务为例,通过 XSL 和一个 groovy 方法来为 Last.fm 提供 feed 格式的数据视图。
1. 第一步当然是创建 sMash 应用程序,这里直接介绍接下来的步骤。打开 AppBuilder 的 Dependencies 标签中的 “Add” 按钮,选中 zero.assemble.flow。
图 10. 使用 zero.assemble.flow 模块2. 为 TrackSearch 服务提供服务描述文件 app/assemble/services/LastfmSearch.xml。
清单 10. 服务描述文件片段
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
    <entry xmlns="http://www.w3.org/2005/Atom"
        xmlns:z="http://www.projectzero.org/assemble/component">
        <title>Last.fm Web Services</title>
        <link rel=
        "http://www.projectzero.org/assemble/component/url-template"
        type="text/xml"
        href="http://ws.audioscrobbler.com/2.0/?method=
        {method}&amp;api_key={apiKey}&amp;artist=
        {artist?}&amp;track={track}"
            />
            ......




3. 创建 XSL 文件 public/stylesheet/lastfm.xsl 将 Last.fm 提供的结果转换成为 Atom feed
清单 11. 格式转换文件片段
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns="http://www.w3.org/2005/Atom"
   xmlnspensearch="http://a9.com/-/spec/opensearch/1.1/">
   <xsl:template match="/">
      <feed><title>
      Search result for <xsl:value-of select=
      "lfm/results/opensearchuery/@searchTerms"/>
      </title>
      <opensearch:totalResults>
       <xsl:value-of select="lfm/results/opensearch:totalResults"/>
      </opensearch:totalResults>
      <xsl:apply-templates select="lfm/results/trackmatches/track"/>
      </feed>
   </xsl:template>
......




4. 在 config/zero.config 中填入你的 API Key:
/config/lastfm/apiKey = "Last.fm API Key: http://www.last.fm/api/account"
5. 最后创建 Groovy 脚本 public/testTrackSearch/index.groovy 调用这个 TrackSearch 服务。这里使用关键词 "Believe" 进行搜索:
清单 12. Groovy 脚本调用 Track Search 服务
1
2
3
4
5
6
7
8
def criteria = [method: "track.search", track: "Believe", format: "atom"]
// use service description file /app/assemble/services/LastfmSearch.xml
def results = invokeService("TrackSearch", criteria)
// rendering
request.view = "XML"
request.xml.output = results
headers.out."Content-Type" = "application/atom+xml"
render()




启动这个应用程序,在浏览器中输入 http://localhost:8080/testTrackSearch 即可看到如图 11 所示的 feed。
图 11. 为 Track Search 服务提供 feed
返回列表