Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

A simple RSS Reader and Podcatcher

Written in Ruby this class reads an RSS feed and downloads the latest enclosure if it exists.

require 'rss/1.0'
require 'rss/2.0'
require 'open-uri'
require 'open-uri'

class Rssreader
  def initialize(url)
    source = url # url or local file
    content = "" # raw content of rss feed will be loaded here
    open(source) do |s| content = s.read end
    @rss = RSS::Parser.parse(content, false)
  end

  # returns the first 3 titles from the rss feed
  def get_summary()
    buffer = '['
    for i in 0..2
      buffer += @rss.items[i.to_i].title + ' | '
    end      
    buffer.slice(0,buffer.length-3) + ']'
  end

  def enclosure?
    @rss.items.to_s.scan('<enclosure').length > 0
  end

  def get_enclosure_url
    enclosure = @rss.items[0].enclosure
    enclosure.url
  end

  def rwget(url, filename)
    file = File.new(filename, 'w')
    file.puts open(url, 'User-Agent' => 'Ruby-wget').read
  end

  def download_enclosure()
    if self.enclosure? then
      enclosure_url = self.get_enclosure_url()
      local_filename = File.basename(enclosure_url)
      #puts local_filename
      if not File.exist?(local_filename) then
        puts 'downloading enclosure ...'
        self.rwget(enclosure_url, local_filename)
        puts 'download completed'
      else
        puts 'enclosure downloaded already'
      end
    end
  end    
end

if __FILE__ == $0
  url = "http://mysite.com/gwd/feed/lugradio.rss"
  rss = Rssreader.new(url)
  puts rss.get_summary()
  rss.download_enclosure()
end

RSS Reader - Reads Name and URL into HashMap

// description of your code here
// RSS reader for web reads them into HashMap



/**
 * Created by IntelliJ IDEA.
 * User: Rapid
 * Date: Oct 9, 2006
 * Time: 3:18:23 PM
 * To change this template use File | Settings | File Templates.
 */
import java.net.URL;
import java.util.Iterator;
import java.util.HashMap;

import com.sun.syndication.feed.module.Module;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/**
 * Reads and prints any RSS/Atom feed type. Adopted from the example by the
 * same name at http://wiki.java.net/bin/view/Javawsxml/Rome05TutorialFeedReader
 *
 */
public class FeedReader {


    HashMap hm = null;
    String[][] rss = null ;
    SyndFeedInput input ;
    URL feedUrl;
    SyndFeed feed ;
    int count =-1;


    public HashMap readRSS(String url) {
        boolean readOk = false;

            try {

                hm = new HashMap();

               feedUrl  = new URL(url);

                input  = new SyndFeedInput();
                 feed = input.build(new XmlReader(feedUrl));

                System.out.println("Title: " + feed.getTitle());
                System.out.println("Author: " + feed.getAuthor());
                System.out.println("Description: " + feed.getDescription());
                System.out.println("Pub date: " + feed.getPublishedDate());
                System.out.println("Copyright: " + feed.getCopyright());
                System.out.println("Modules used:");



                String metaRSS = "Title: " + feed.getTitle() + "\n" +
                "Author: " + feed.getAuthor()  + "\n" +
                 "Description: " + feed.getDescription()  + "\n" +
                 "Pub date: " + feed.getPublishedDate()  + "\n" +
                 "Copyright: " + feed.getCopyright() ;




                rss = new String[ feed.getEntries().size()][2];


                System.out.println("Titles of the " + feed.getEntries().size() +
                                   " entries:");
                for (final Iterator iter = feed.getEntries().iterator();
                     iter.hasNext();)
                {






                    rss[++count][0] =      ((SyndEntry)iter.next()).getTitle().toString();




                }
                count = -1 ;
                for (final Iterator iter = feed.getEntries().iterator();
                     iter.hasNext();)
                {

                   rss[++count][1] =      ((SyndEntry)iter.next()).getUri().toString();
                }


                if (feed.getImage() != null)
                {
                    System.out.println("Feed image URL: " +
                                       feed.getImage().getUrl());
                }

                readOk = true;
                hm.put( feed.getTitle(), rss);
            }
            catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("ERROR: " + ex.getMessage());
            }


        String[][] rs = (String[][])hm.get("LinuxInsider");

          System.out.println("************************");
        for( int i=0; i<rs.length; i++){

            System.out.println( rs[i][0]);
             System.out.println( rs[i][1]);
//             System.out.println( rs[i][2]);
        }
        if (! readOk) {
            System.out.println();
            System.out.println("FeedReader reads and prints info on any RSS/Atom feed.");
            System.out.println("The first parameter must be the URL of the feed to read.");
            System.out.println();
        }

        return hm;
    }

}

RSS Reader - simple with Main

// description of your code here
//Reads rss from given url



/**
 * Created by IntelliJ IDEA.
 * User: Rapid
 * Date: Oct 9, 2006
 * Time: 3:18:23 PM
 * To change this template use File | Settings | File Templates.
 */
import java.net.URL;
import java.util.Iterator;

import com.sun.syndication.feed.module.Module;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/**
 * Reads and prints any RSS/Atom feed type. Adopted from the example by the
 * same name at http://wiki.java.net/bin/view/Javawsxml/Rome05TutorialFeedReader
 *
 */
public class FeedReader1 {

    public static void main(final String[] args) {
        boolean readOk = false;
        if (args.length == 1) {
            try {
                final URL feedUrl = new URL(args[0]);

                final SyndFeedInput input = new SyndFeedInput();
                final SyndFeed feed = input.build(new XmlReader(feedUrl));

                System.out.println("Title: " + feed.getTitle());
                System.out.println("Author: " + feed.getAuthor());
                System.out.println("Description: " + feed.getDescription());
                System.out.println("Pub date: " + feed.getPublishedDate());
                System.out.println("Copyright: " + feed.getCopyright());
                System.out.println("Modules used:");
                for (final Iterator iter = feed.getModules().iterator();
                     iter.hasNext();)
                {
                    System.out.println("\t" + ((Module)iter.next()).getUri());
                }
                System.out.println("Titles of the " + feed.getEntries().size() +
                                   " entries:");
                for (final Iterator iter = feed.getEntries().iterator();
                     iter.hasNext();)
                {
                    System.out.println("\t" +
                                       ((SyndEntry)iter.next()).getTitle());
                    
                }
                if (feed.getImage() != null)
                {
                    System.out.println("Feed image URL: " +
                                       feed.getImage().getUrl());
                }

                readOk = true;
            }
            catch (Exception ex) {
                ex.printStackTrace();
                System.out.println("ERROR: " + ex.getMessage());
            }
        }

        if (! readOk) {
            System.out.println();
            System.out.println("FeedReader reads and prints info on any RSS/Atom feed.");
            System.out.println("The first parameter must be the URL of the feed to read.");
            System.out.println();
        }
    }
}

Math Parser //JavaScript Class


This class is able to parse math expressions and also run user defined functions.

On JavaScript there's the "eval" function, that can do such things well, but this code objective was just to give me fun or a new challenge =)~

[UPDATED CODE AND HELP CAN BE FOUND HERE]

Usage:

x = new MathProcessor;
try{alert(x.parse("1+2-(3*4) + medium(2,3) - frac( 2.2231)"));}
catch(e){alert(e);}


It's possible to add more functions to the class, just add them into the "methods" property ;]

Well, that's it :)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/math-processor [v1.0]

MathProcessor = function(){ //v1.0
    var o = this;
    o.o = {
        "+": function(a, b){ return +a + b; },
        "-": function(a, b){ return a - b; },
        "%": function(a, b){ return a % b; },
        "/": function(a, b){ return a / b; },
        "*": function(a, b){ return a * b; },
        "^": function(a, b){ return Math.pow(a, b); },
        "~": function(a, b){ return Math.sqrt(a, b); }
    };
    o.s = { "^": 3, "~": 3, "*": 2, "/": 2, "%": 1, "+": 0, "-": 0 };
    o.u = {"+": 1, "-": -1}, o.p = {"(": 1, ")": -1};
};

MathProcessor.prototype.parse = function(e){
    for(var n, x, o = [], s = [x = this.RPN(e.replace(/ /g, "").split(""))]; s.length;)
        for((n = s[s.length-1], --s.length); n[2]; o[o.length] = n, s[s.length] = n[3], n = n[2]);
    for(; (n = o.pop()) != undefined; n[0] = this.o[n[0]](isNaN(n[2][0]) ? this.f(n[2][0]) : n[2][0], isNaN(n[3][0]) ? this.f(n[3][0]) : n[3][0]));
    return +x[0];
};

MathProcessor.prototype.methods = {
    "div": function(a, b){ return parseInt(a / b); },
    "frac": function(a){ return a - parseInt(a); },
    "sum": function(n1, n2, n3, n){ for(var r = 0, a, l = (a = arguments).length; l; r += a[--l]); return r; },
    "medium": function(a, b){ return (a + b) / 2; }
};

MathProcessor.prototype.error = function(s){
    throw new Error("MathProcessor: " + (s || "Erro na expressão"));
}

MathProcessor.prototype.RPN = function(e){
    var _, r, c = r = [, , , 0];
    if(e[0] in this.u || !e.unshift("+"))
        for(; e[1] in this.u; e[0] = this.u[e.shift()] * this.u[e[0]] + 1 ? "+" : "-");
    (c[3] = [this.u[e.shift()], c, , 0])[1][0] = "*", (r = [, , c, 0])[2][1] = r;
    (c[2] = this.v(e))[1] = c;
    (!e.length && (r = c)) || (e[0] in this.s && ((c = r)[0] = e.shift(), !e.length && this.error()));
     while(e.length){
        if(e[0] in this.u){
            for(; e[1] in this.u; e[0] = this.u[e.shift()] * this.u[e[0]] + 1 ? "+" : "-");
            (c = c[3] = ["*", c, , 0])[2] = [-1, c, , 0];
        }
        (c[3] = this.v(e))[1] = c;
        e[0] in this.s && (c = this.s[e[0]] > this.s[c[0]] ?
            ((c[3] = (_ = c[3], c[2]))[1][2] = [e.shift(), c, _, 0])[2][1] = c[2]
            : r == c ? (r = [e.shift(), , c, 0])[2][1] = r
            : ((r[2] = (_ = r[2], [e.shift(), r, ,0]))[2] = _)[1] = r[2]);
    }
    return r;
};

MathProcessor.prototype.v = function(e){
    if("0123456789.".indexOf(e[0]) + 1){
        for(var i = -1, l = e.length; ++i < l && "0123456789.".indexOf(e[i]) + 1;);
        return [+e.splice(0,i).join(""), , , 0];
    }
    else if(e[0] == "("){
        for(var i = 0, l = e.length, j = 1; ++i < l && (e[i] in this.p && (j += this.p[e[i]]), j););
        return this.RPN(l = e.splice(0,i), l.shift(), !j && e.shift());
    }
    else{
        var i = 0, c = e[0].toLowerCase();
        if((c >= "a" && c <= "z") || c == "_"){
            while(((c = e[++i].toLowerCase()) >= "a" && c <= "z") || c == "_" || (c >= 0 && c <= 9));
            if(c == "("){
                for(var l = e.length, j = 1; ++i < l && (e[i] in this.p && (j += this.p[e[i]]), j););
                return [e.splice(0,i+1).join(""), , , 0];
            }
        }
    }
    this.error();
}

MathProcessor.prototype.f = function(e){
    var i = 0, n;
    if(((e = e.split(""))[i] >= "a" && e[i] <= "z") || e[i] == "_"){
        while((e[++i] >= "a" && e[i] <= "z") || e[i] == "_" || (e[i] >= 0 && e[i] <= 9));
        if(e[i] == "("){
            !this.methods[n = e.splice(0, i).join("")] && this.error("Função \"" + n + "\" não encontrada"), e.shift();
            for(var a = [], i = -1, j = 1; e[++i] && (e[i] in this.p && (j += this.p[e[i]]), j);)
                j == 1 && e[i] == "," && (a.push(this.parse(e.splice(0, i).join(""))), e.shift(), i = -1);
            a.push(this.parse(e.splice(0,i).join(""))), !j && e.shift();
        }
        return this.methods[n].apply(this, a);
    }
};

Digg/RSS Reader

Grabs the RSS-feed from digg.com and reads it out
loud using festival.

#!/bin/sh
# Copyright (c) 2005 Davor Babic <davorb@gmail.com>
# All rights reserved.
# Usage of the works is permitted provided that this
# instrument is retained with the works, so that any
# entity that uses the works is notified of this
# instrument.
# DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.

url="http://digg.com/rss/index.xml"

echo "Parsing RSS..."
curl --silent "$url" | grep -E '(title>|description>)' | \
        sed -n '4,$p' | \
	sed -e 's/<title>//' -e 's/<\/title>//' -e 's/<description>/  /' \
	    -e 's/<\/description>//' | head -5 > digg 
echo "Reading..."
festival --tts digg
rm -rf ./digg
echo "Done."
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS