Grab Headlines From A Remote RSS File
By Nicholas Chase
2003-12-19
Reader Rating:

Caching The Feed
This system would work fine on a personal server where you're the only one accessing it, but in the real world, it would be impractical (and rude) to pull the feed every time someone wants to read it. Instead, you need to build the system with some sort of time delay, so if the feed's been pulled recently, the existing headlines.html file is used.
To do that, you can take advantage of a Java application's nature. A static variable that represents the last time the feed was pulled would be constant for all instances of the RSSProcessor class, so you can check the current time against it before actually pulling the feed:
Listing 10. Choosing a stylesheet
import java.util.Date;
public class RSSProcessor {
...
static Date _LastUpdated = new Date();
public Date getLastUpdated(){
return _LastUpdated;
}
public void setRSSFile(String fileName){
Date now = new Date();
long diff = now.getTime() - _LastUpdated.getTime();
double interval = .5;
if ((diff == 0) || (diff > (interval * 60 * 1000))){
_LastUpdated = now;
try {
InputSource docFile = new InputSource (fileName);
...
Transformer transformer = transFactory.newTransformer(finalStyle);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
The first time the server instantiates RSSProcessor, _LastUpdated gets initialized with the current date. At (essentially) the same time, the server executes the setRSSFile() method, and because the difference between the current time and the _LastUpdated time is zero, the transformation takes place.
The next time someone calls the page, a new instance of RSSProcessor is created, but because _LastUpdated is static, the new instance sees the existing value of _LastUpdated rather than initializing it. The interval is measured in minutes, with the difference between _LastUpdated and the current time measured in milliseconds. If the amount time that has elapsed is less than the interval, nothing else happens. The headlines.html file isn't updated, so the server uses the old one instead.
If, on the other hand, the interval has passed, _LastUpdated gets the current time, which is passed on to any subsequent RSSProcessor objects, and the bean pulls a new copy of the feed to transform.
First published by
IBM developerWorks
If you found this article interesting, you may want to read these as well:
» Better SOAP Interfaces With Header Elements
» Variable Substitution In XML Documents
» Create JPEGs Automatically With SVG
» Tip: Convert from HTML to XML with HTML Tidy
|