Monday, October 28

RSS Feed with Java And AJAX

Introduction: A number of websites, news services, blogs, audios and video provide RSS content. RSS is a method of syndicating content and publish frequently updated information. RSS stands for Really Simple Syndication (or Rich Site Summary, and also RDF Site Summary). Nowadays, RSS has become the dominant format for distributing updated web contents on the Web. RSS is a protocol, an application of XML which provides an open method for making web feeds available from a site in order to provide other people with a summary of the website's recently added content. RSS is changing the world of publishing news and searching for news. Thus, RSS feeds are the most beneficial and faster way of submitting updated content to subscribers.
Benefit of RSS Feed:
  • Feeds show all updated information in a single file at a specific location. You save time by not needing to visit each site individually.
  • It ensures your privacy, by not needing to join each site's email newsletter
  • RSS feeds make it possible to view brief information about the content without visiting a webpage.
How RSS feed works:
·         News-related sites, weblogs, and other online publishers create their updated web content with headlines, links, descriptions, summaries etc. in XML format, and they provide a link to that file.
·         A Feed Aggregator collects the feed and creates a topic-wise index on the available feeds.
·         A Feed Reader reads the feeds and displays those feeds to the user in a prescribed format.
·         User can view the updated content from their PC with the help of the Feed Reader.
·         The links in a feed are used for further reading if the user is interested
What does RSS look like
<rss version="2.0">
  <channel>
    <title>Some Title</title>
    <link>http://www.domain.com/</link>
    <description>description</description>
<Language>language</Language>
    <item>
      <title>Title</title>
      <link>URL </link>
      <description>Description</description>
    </item>
        
</channel>
</rss>



An RSS feed uses tags in brackets <> for defining its contents. Lots of RSS tags are optional. Following is a summary of the different RSS tags:
The contents of RSS feeds are called items. These items are combined with related data. Every item contains three or more sub-items. The common of those are:
·         Title - Same as the name of the website.
·         Description - A brief information about the content.
·         Link - The referral URL where the actual content is located
RSS feed channel
A channel is container of items; in other words, all items in an RSS feed make a channel. A channel shows how items co-relate with each other. Channels also have a title, description, and tags, similar to items. Along with these elements, a channel can have some more elements:
·         pubDate - The date of content publication.
·         language - Language of the channel.
·         Copyright - Copyright notice.
·         Webmaster - The email address that can be used for dealing with technical problems.
·         Category - Denotes the category of the contents.
·         Generator - Contains the name of the program that created the feed.
·         Skip Days - Shows the number of days when you do not need to check for changes in the feed.
·         Cloud - Enables us to register with a cloud server, for getting informed about changes in the feeds.
Here I’ll create a very simple RSS reader in Java. It reads ESPN RSS to get college basketball news.
Later I’ll call Google RSS Feed Ajax API to get the same results.
RSS Reader in Java:
import java.net.MalformedURLException;
import java.net.URL;  
import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
import org.w3c.dom.Document;  
import org.w3c.dom.Element;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  


public class RSS {

   private static RSS instance = null;

   private URL rssURL;

   private RSS() {}

   public static RSS getInstance() {
      if (instance == null)
         instance = new RSS();
      return instance;
   }

   public void setURL(URL url) {
      rssURL = url;
   }

   public void writeFeed() {
      try {
                  //DOM Builder
         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        //Load URL and Parse
         Document doc = builder.parse(rssURL.openStream());
      
        
         //get item element
         NodeList items = doc.getElementsByTagName("item");
            //Loop through items
         for (int i = 0; i < items.getLength(); i++) {
            Element item = (Element)items.item(i);
            //display title, description,link,pubdate and author
            System.out.println("Title: " + getValue(item, "title"));
            System.out.println("Description: " + getValue(item, "description"));
            System.out.println("Link: " + getValue(item, "link"));
            System.out.println("Publish Date: " + getValue(item,"pubDate"));
            System.out.println("Author: " + getValue(item,"dc:creator"));
            System.out.println();
         }
      } catch (Exception e) {
        e.printStackTrace();
      }
     
  }

   public String getValue(Element parent, String nodeName) {
      return parent.getElementsByTagName(nodeName).item(0).getFirstChild().getNodeValue();
   }

   public static void main(String[] args) {
      try {
         RSS reader = RSS.getInstance();
       //URL to feed
         reader.setURL(new URL("http://sports.espn.go.com/espn/rss/ncb/news"));
         reader.writeFeed();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

Output:
Title: ESPN.com Power Rankings 2013
Description: Top 25 Rankings
Link: http://espn.go.com/ncb/feature/video/_/page/preseason-power-rankings-2013-2014/power-rankings-2013
Publish Date: Mon, 28 Oct 2013 09:16:29 PDT
Author: FlashFeature

Title: Gasaway: Top 5 offenses for 2013-14
Description: Projecting most efficient offenses in college basketball for upcoming season
Link: http://insider.espn.go.com/mens-college-basketball/story/_/id/9878567/kentucky-wildcats-top-projected-offenses-2013-14-college-basketball
Publish Date: Mon, 28 Oct 2013 06:39:59 PDT
Author: John Gasaway

Title: Top juco player Allen commits to Arizona
Description: Kadeem Allen, one of the top junior college players in the nation, has committed to Sean Miller and the Arizona Wildcats, he told ESPN.com on Monday.
Link: http://espn.go.com/recruiting/basketball/story/_/id/9892742/kadeem-allen-commits-sean-miller-arizona-wildcats
Publish Date: Mon, 28 Oct 2013 10:10:31 PDT
Author: Jeff Goodman

Title: Big East adds Jernstedt as senior adviser
Description: Longtime NCAA executive Tom Jernstedt has been appointed senior adviser to the Big East Conference.
Link: http://espn.go.com/mens-college-basketball/story/_/id/9895084/big-east-tabs-tom-jernstedt-senior-adviser
Publish Date: Mon, 28 Oct 2013 16:09:33 PDT
Author: Associated Press

Title: Purdue suspends Hammons, cites team rules
Description: Purdue center A.J. Hammons was suspended Monday for three games for violating team rules.
Link: http://espn.go.com/mens-college-basketball/story/_/id/9892817/purdue-boilermakers-suspend-aj-hammons-cites-team-rules
Publish Date: Mon, 28 Oct 2013 17:57:42 PDT
Author: Associated Press

RSS Feed with Google AJAX API:
<head>
<script type="text/javascript" src="http://www.google.com/jsapi?key=Your API KEY ">
</script>

<script type="text/javascript">
//Load Google Ajax Feed API (version 1)
google.load("feeds", "1")
</script>
</head>

<body>
<div id="rssdiv"></div>

<script type="text/javascript">
// your choice of URL

var feedurl="http://sports.espn.go.com/espn/rss/ncb/news"  var feedlimit=20  //# results return
var feedOutput="<b>College Basketball Headlines From ESPN :</b><br /><ul>"

function feedsetup(){

//Google Feed API method Google Feed Object Class that accepts a single RSS //feed baed on "URL" parameter
var feedURL=new google.feeds.Feed(feedurl)

 //Google Feed API method
feedURL.setNumEntries(feedlimit)

//Google Feed API method Downloads the feed specified during initialization of the Ajax Feed Class and once it's complete, it invokes the callback Function
feedURL.load(feedResult)
}

function feedResult(result){
//if no error in fetching RSS feed
if (!result.error){
//get feed contents JSON ARRAY

var myFeeds=result.feed.entries
for (var i=0; i<myFeeds.length; i++){
var entrydate=new Date(myFeeds[i].publishedDate) //get date of entry
var entrydatestr=' '+entrydate.getFullYear()+"/"+(entrydate.getMonth()+1)+"/"+entrydate.getDate()
feedOutput+="<p><a href='" + myFeeds[i].link + "'>" + myFeeds[i].title + "</a><br/>" + "Published :" + entrydatestr + "<br />" + "Author: " + myFeeds[i].author + "</br>" +
 myFeeds[i].content +  "</p>"
}
document.getElementById("rssdiv").innerHTML=feedOutput


}
else
alert("Error fetching feeds!") // alert there is some error in fetching
}

window.onload=function(){
feedsetup()
}

</script>

</body>
</html>

Output:

College Basketball Headlines From ESPN :
O'Neil: Enfield chasing the impossible -- again
Published : 2013/10/28
Author: Dana O'Neil
He made the impossible happen at FGCU; can he do it with the Trojans?
Top juco player Allen commits to Arizona
Published : 2013/10/28
Author: Jeff Goodman
Kadeem Allen, one of the top junior college players in the nation, has committed to Sean Miller and the Arizona Wildcats, he told ESPN.com on Monday.
Big East adds Jernstedt as senior adviser
Published : 2013/10/28
Author: Associated Press
Longtime NCAA executive Tom Jernstedt has been appointed senior adviser to the Big East Conference.
Purdue suspends Hammons, cites team rules
Published : 2013/10/28
Author: Associated Press
Purdue center A.J. Hammons was suspended Monday for three games for violating team rules.

2 comments:

Vomail said...

Hey, I had an amazing time reading all of these details. I am also going to start promoting my business and have been learning various things for the online world. I think that the Adwords Marketing would be the best option as per my current research. What is your opinion?

Unknown said...

This Website is great

Post a Comment