Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion, Adobe Flex

ColdFusion: Article

ColdFusion Developer's Journal: Feed Your Site

Incorporating RSS and Atom feeds into your ColdFusion Site

Code reuse has always been an important principle in a software developer's toolbox. While this principle often applies to source code, developers have also tried to apply the same formula to Web content. By grabbing content from one Web site, the developer can reuse it in new and unique ways.

Traditionally, reusing content meant writing screen scrapers that could sift through a heavy table-filled HTML page to extract the few data elements of interest. If the source page's layout changed, the extraction code would usually have to be rewritten too.

All this changed when Web syndication feeds were introduced several years ago. A standard file format, such as RSS, meant that the same tools could be reused for many different sets of data. A Web designer could also rebuild his site at any time without worrying that someone else's extraction script would no longer function. While Web syndication files have been around for quite some time, the last couple of years they've really taken off. With so many news feeds available, now is an excellent time to take advantage of their power. The purpose of this article is to address how to use ColdFusion to consume Web syndication feeds, as well as how to generate your own news feeds.

What Are RSS and Atom?
RSS stands for Rich-Site Summary or Really Simple Syndication depending on who you ask. It's a file format used in Web syndication and defined using XML. A RSS file contains metadata about the news feed or channel elements and a set of news items. Each news item usually contains the item's title, a brief summary of the news item, and a link to the full news story. Since RSS is nothing more than an XML file, there's a rich supply of tools and APIs that can both generate and read RSS feeds. Atom is another Web syndication file format, with a primary purpose of addressing some of the limitations of the RSS 2.0 specification. The Atom format is different enough from RSS 2.0 that great care must be taken when trying to build a reader that consumes all kinds of feed formats. Thankfully, the file formats are comparable enough that the same parser can be used for most common uses.

You can read, or consume, a feed with one of the many freely available programs, but what's the fun in that? Let's find out just how easy it is to use ColdFusion to read news feeds.

How to Read a Feed
As mentioned, one of the issues with trying to consume a feed is the differences in file formats among the different feed specifications. Because of the differences in both structure and element names between the different feeds, writing a feed parser can be difficult. Fortunately, someone has already done the work for you.

Roger Benningfield's RssAtom ColdFusion Component (CFC) will normalize the content of RSS 0.91, RSS 1.0, RSS 2.0, Atom 0.3, and Atom 1.0 feeds into a feed-neutral data structure. The primary function in this CFC, normalize, returns a structure. One element in the structure, feed, contains header elements and their values, while a second element, items, contains an array of items and their content. A dump of this structure looks like Figure 1. This structure is much easier to work with than trying to account for the feed differences yourself. To run each of the examples accompanying this article, you'll have to get the latest version of RssAtom.cfc from Roger's site (http://mxblogspace.journurl.com/users/admin/).

example1.cfm reads one of the aggregated feeds from fullasagoog.com using the <cfhttp> tag and normalizes the feed using RssAtom.cfc. Finally, it displays some of the header information and iterates through each news items, showing title, link, and content for each item. Figure 2 has an example of what the results look like. The page's code weighs in at only 27 lines, but what if we wanted to include several feeds on one Web page? Because the repetitive code quickly adds up, let's create a custom tag to encapsulate the feed consumption and display code.

Building a Custom Tag
Moving the existing code into a custom tag is easy, but let's add some additional functionality while we're at it. Let's also allow our tag user to specify the format in which he'd like to return the feed results. rssdisplay.cfm contains the code for this custom tag. A call to this custom tag looks like this:

<cf_rssdisplay url="{feed url]" file="{or absolute path to feed}">
<format>
<header><![CDATA[<h2><a
href="${link}">${title}</a></h2><ul>]]></header>
<items><![CDATA[<li><a
href="${link}">${title}</a></li>]]></items>
<footer><![CDATA[</ul>]]></footer>
</format>
</cf_rssdisplay>

To format the feed, the tag will display the header once, replacing the variables, indicated as ${variable} with data from the feed header. It will then do the same thing for each item, except that it will use the item's format rule and replace each variable with item data. Finally, it will run the footer once, doing any necessary variable replacement. example2.cfm uses the custom tag and results in the same output as example1.cfm. The code in example2.cfm is not only shorter, but makes us flexible in how we present the feed data.

Putting the Reader on a Diet
The custom tag makes it much easier to add feeds to any ColdFusion template that we care to add them to, but it suffers from one big problem. Each time the tag is called, it has to access the remote feed. This slows down how quickly the tag runs on your site and uses up someone else's bandwidth needlessly. It doesn't have to consume the feed on every page access, particularly since the feed most likely doesn't change every time that we access it. Let's add a couple of new attributes to the rssdisplay.cfm custom tag that will let us specify when and how to cache a feed.

cachedWithin will accept a time span that specifies how often the cache should be refreshed. name will give the cached feed a unique name to identify the cached feed. That way, if we want to display the same feed two different ways, both can use the same cached copy of the feed. rssdisplay2.cfm contains the modifications to implement caching. The caching code adds a little over 50 lines of code to the tag, with most of the changes between lines 29 and 70. I opted to cache the feeds in the server scope instead of the application scope or session scope so the tag could be called on any page, not just one that's part of an application. It's a trivial matter to change the caching to the application scope, if desired. Now that we've added the ability to cache feeds via the custom tag, all we have to figure out is how often this particular feed we're consuming is updated. Surely, the feed doesn't change that often, but is there a way to find out how frequently it changes?

Many feeds will include some information about how often they're updated. We can use this information to determine how often to retrieve a feed. RSS 2.0 feeds have a "time to live" element, or ttl, that indicates in minutes how often the feed is updated. The particular feed that we've been working with is a RSS 1.0 feed that includes the Syndication module. Using the three elements that comprise the Syndication module, updatePeriod, updateFrequency, and updateBase, we can figure out how often the feed is updated. This particular feed is updated every hour. example3.cfm uses the updated <cf_rssdisplay> tag, and caches the feed once an hour. Notice that it's more responsive than example2.cfm. Caching will help make your site run faster and will respect the source feed's update instructions.

Feeding Ourselves
If the news items that you're interested in aren't currently available, perhaps it's time for you to generate your own news feed. Then too, there might be other sources of news items that you might not consider news. While news feeds are primarily used for news articles and blog entries, there are plenty of other news sources. If news is nothing more than a time-sensitive event or entry, then each entry in a Web server error log is a piece of news. One thing that would be useful is a news feed that presents the most recent records from the ColdFusion server's application.log file. That way, I know what kind of errors are occurring on my server without logging into the ColdFusion administrator.

example4.cfm builds a feed that displays the 20 most recent entries in the application.log file. I decided to use the RSS 2.0 format for the feed simply because it's easy to work with and I'm most familiar with it. First the code builds the root and header portion of the feed using ColdFusion's XML functions. It then reads the last 20 records in the file, splits them into fields by column, and creates a new item using the column data. Figure 3 shows what the resulting XML feed looks like in Firefox.

Consuming Our New Feed
Now that we've got this new feed, let's use it to build a simple administrator dashboard. Besides our new application news feed we'll also present the feeds for ColdFusion and JRun TechNotes. That way we have known issues at our fingertips if we come across a weird error in the ColdFusion logs. example5.cfm contains the code to build this little dashboard. Notice that it is only 34 lines long because the RssAtom.cfc and the custom tag do most of the work. In these few lines, we're retrieving, caching, and displaying three separate feeds, each feed having its own style. The results are shown in Figure 4.

Please see Source Code zip file.

Summary
RSS feeds are useful for both sharing and displaying information, and more and more Web sites are providing news feeds of their data. ColdFusion, along with an excellent ColdFusion component, provides us with the tools to consume these news feeds easily. RSS feeds provide yet another channel to communicate information, and I encourage you to find ways in your daily management and development tasks to take advantage of this simple yet, powerful XML file format.

More Stories By Jeremy Lund

Jeremy Lund is the manager of the Web Resource Center at University Health Care in Salt Lake City, Utah (http://uuhsc.utah.edu/wrc/). As the manager he coordinates development efforts, designs their Web architecture, and, in the time left, develops Web applications. He has worked with Internet technologies for over seven years, and enjoys working not only with ColdFusion, Java, and Perl, but is also an advocate of using XHTML and CSS. Jeremy received a bachelor's degree in computer engineering from the University of Utah, and is a Sun Certified Programmer for the Java 2 platform.

Comments (2) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
SYS-CON India News Desk 06/20/06 07:08:44 PM EDT

Code reuse has always been an important principle in a software developer's toolbox. While this principle often applies to source code, developers have also tried to apply the same formula to Web content. By grabbing content from one Web site, the developer can reuse it in new and unique ways.

CFDJ News Desk 06/20/06 05:54:15 PM EDT

Code reuse has always been an important principle in a software developer's toolbox. While this principle often applies to source code, developers have also tried to apply the same formula to Web content. By grabbing content from one Web site, the developer can reuse it in new and unique ways.

@ThingsExpo Stories
Announcing Poland #DigitalTransformation Pavilion
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
CloudEXPO | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
In past @ThingsExpo presentations, Joseph di Paolantonio has explored how various Internet of Things (IoT) and data management and analytics (DMA) solution spaces will come together as sensor analytics ecosystems. This year, in his session at @ThingsExpo, Joseph di Paolantonio from DataArchon, added the numerous Transportation areas, from autonomous vehicles to “Uber for containers.” While IoT data in any one area of Transportation will have a huge impact in that area, combining sensor analytic...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
I think DevOps is now a rambunctious teenager - it's starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.