Updates from July, 2007 Toggle Comment Threads | Keyboard Shortcuts

  • Subinkrishna Gopi 10:17 am on July 26, 2007 Permalink |  

    An Ajax Rss feed reader 

    Ajax (Asynchronous Javascript And Xml)
    I hopemost of you guys know what Ajax (some people say its AJAX) is all about. Ajax is nothing but a way to make website more fast & dynamic by minimizing the amount of request/response data. This is achieved with the help of JavaScript (more precisely we can say, using XmlHttpRequest).

    JavaScript:

    // Initializing the url connection 
    // Connecting to server URL 
    // Eg: getFeed.jsp?feedUrl=www.mywebsite.com/feeds.xml 
    function http_initDataTransfer(url)   
    { 
     if(connObj == null) 
     { 
      connObj = http_getHttpConnector(); 
      if(connObj != null) 
      { 
         http_setConnectionObject(connObj); 
      } 
      else 
      { 
         ui_showErrorMessage("No Browser Support"); 
         return; 
      } 
     }  
    
     connObj.open("GET", url); 
     connObj.onReadyStateChange = http_handleStateChange; 
     connObj.send(null);  
    } 
    // Creating browser dependent XMLHttpTequest object 
    function http_getHttpConnector()   
    { 
       try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}  // MS IE 
       try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}  // MS IE 
       try { return new XMLHttpRequest(); } catch(e) {}      // Others 
       return (null); 
    }
    // Connection state change handler 
    function http_handleStateChange()  
    { 
      if (connObj.readyState == 4) 
      { 
        if (connObj.status == 200) 
        { 
          var tmpFeedData = connObj.responseText; 
          if(tmpFeedData != null) 
            // Update the view - User defined 
            ui_updateFeed(tmpFeedData);  
    
          else 
            // Show error message - User defined 
            ui_showErrorMessage("Response Error"); 
        } 
        else 
          ui_showErrorMessage("Network Error"); 
      } 
    }

    RSS (Really Simple Syndication)
    RSS is way to publish frequently changing contents like blog posts, news updates, stock quotes & things like that. An RSS document, which is called a “feed,” “web feed,” or “channel,” contains either a summary of content from an associated web site or the full text. RSS formats are specified using XML, a generic specification for the creation of data formats.

    I have already posted a SAX based RSS feed parser here. Use this class to get the feed data from the URL and send it as the response in the form of JSON or some other application dependent format.

    Use org.json Java API to enable JSON support. Get org.json

    Advertisements
     
  • Subinkrishna Gopi 3:13 pm on July 25, 2007 Permalink |
    Tags: feeds, , , , sax, ,   

    RSS Parser (SAX) 

    RSS (Really Simple Syndication)
    RSS is way to publish frequently changing contents like blog posts, news updates, stock quotes & things like that. An RSS document, which is called a “feed,” “web feed,” or “channel,” contains either a summary of content from an associated web site or the full text. RSS formats are specified using XML, a generic specification for the creation of data formats.

    I have attached a simple SAX parser for RSS. Please let me know if there is any flaw in the attached code. This code is provided for learning purpose with less focus on coding standards & it’s efficiency. You are free to use & modify it.

    package subin.rnd.xml;
    import java.io.IOException; 
    import java.io.InputStream; 
    import java.net.URL; 
    import java.util.ArrayList; 
    import java.util.HashMap; 
    import java.util.Properties;
    import javax.xml.parsers.SAXParser; 
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes; 
    import org.xml.sax.helpers.DefaultHandler;
    public class RssParser extends DefaultHandler 
    {   
        private String        urlString; 
        private RssFeed       rssFeed; 
        private StringBuilder text; 
        private Item          item; 
        private boolean       imgStatus; 
        
        public RssParser(String url) 
        { 
            this.urlString = url; 
            this.text = new StringBuilder(); 
        } 
        
        public void parse() 
        { 
            InputStream urlInputStream = null; 
            SAXParserFactory spf = null; 
            SAXParser sp = null; 
            
            try 
            { 
                URL url = new URL(this.urlString); 
                _setProxy(); // Set the proxy if needed 
                urlInputStream = url.openConnection().getInputStream();            
                spf = SAXParserFactory.newInstance(); 
                if (spf != null) 
                { 
                    sp = spf.newSAXParser(); 
                    sp.parse(urlInputStream, this); 
                } 
            }
            /* 
             * Exceptions need to be handled 
             * MalformedURLException 
             * ParserConfigurationException 
             * IOException 
             * SAXException 
             */ 
            
            catch (Exception e) 
            { 
                System.out.println("Exception: " + e); 
                e.printStackTrace(); 
            } 
            finally 
            { 
                try 
                { 
                    if (urlInputStream != null) urlInputStream.close(); 
                } 
                catch (Exception e) {} 
            } 
        }
        public RssFeed getFeed() 
        { 
            return (this.rssFeed); 
        } 
        
        public void startElement(String uri, String localName, String qName, 
                Attributes attributes) 
        { 
            if (qName.equalsIgnoreCase("channel")) 
                this.rssFeed = new RssFeed(); 
            else if (qName.equalsIgnoreCase("item") && (this.rssFeed != null)) 
            { 
                this.item = new Item(); 
                this.rssFeed.addItem(this.item); 
            } 
            else if (qName.equalsIgnoreCase("image") && (this.rssFeed != null)) 
                this.imgStatus = true; 
        } 
        
        public void endElement(String uri, String localName, String qName) 
        { 
            if (this.rssFeed == null) 
                return; 
            
            if (qName.equalsIgnoreCase("item")) 
                this.item = null; 
            
            else if (qName.equalsIgnoreCase("image")) 
                this.imgStatus = false; 
            
            else if (qName.equalsIgnoreCase("title")) 
            { 
                if (this.item != null) this.item.title = this.text.toString().trim(); 
                else if (this.imgStatus) this.rssFeed.imageTitle = this.text.toString().trim(); 
                else this.rssFeed.title = this.text.toString().trim(); 
            }        
            
            else if (qName.equalsIgnoreCase("link")) 
            { 
                if (this.item != null) this.item.link = this.text.toString().trim(); 
                else if (this.imgStatus) this.rssFeed.imageLink = this.text.toString().trim(); 
                else this.rssFeed.link = this.text.toString().trim(); 
            }        
            
            else if (qName.equalsIgnoreCase("description")) 
            { 
                if (this.item != null) this.item.description = this.text.toString().trim(); 
                else this.rssFeed.description = this.text.toString().trim(); 
            } 
            
            else if (qName.equalsIgnoreCase("url") && this.imgStatus) 
                this.rssFeed.imageUrl = this.text.toString().trim(); 
            
            else if (qName.equalsIgnoreCase("language")) 
                this.rssFeed.language = this.text.toString().trim(); 
            
            else if (qName.equalsIgnoreCase("generator")) 
                this.rssFeed.generator = this.text.toString().trim(); 
            
            else if (qName.equalsIgnoreCase("copyright")) 
                this.rssFeed.copyright = this.text.toString().trim(); 
            
            else if (qName.equalsIgnoreCase("pubDate") && (this.item != null)) 
                this.item.pubDate = this.text.toString().trim(); 
            
            else if (qName.equalsIgnoreCase("category") && (this.item != null)) 
                this.rssFeed.addItem(this.text.toString().trim(), this.item); 
            
            this.text.setLength(0); 
        } 
        
        public void characters(char[] ch, int start, int length) 
        { 
            this.text.append(ch, start, length); 
        } 
        
        public static void _setProxy() 
        throws IOException 
        { 
            Properties sysProperties = System.getProperties(); 
            sysProperties.put("proxyHost", "<Proxy IP Address>"); 
            sysProperties.put("proxyPort", "<Proxy Port Number>"); 
            System.setProperties(sysProperties); 
        } 
       
        public static class RssFeed 
        { 
            public  String title; 
            public  String description; 
            public  String link; 
            public  String language; 
            public  String generator; 
            public  String copyright; 
            public  String imageUrl; 
            public  String imageTitle; 
            public  String imageLink; 
            
            private ArrayList <Item> items; 
            private HashMap <String, ArrayList <Item>> category; 
            
            public void addItem(Item item) 
            { 
                if (this.items == null) 
                    this.items = new ArrayList<Item>(); 
                this.items.add(item); 
            } 
            
            public void addItem(String category, Item item) 
            { 
                if (this.category == null) 
                    this.category = new HashMap<String, ArrayList<Item>>(); 
                if (!this.category.containsKey(category)) 
                    this.category.put(category, new ArrayList<Item>()); 
                this.category.get(category).add(item); 
            } 
        } 
        
        
        public static class Item 
        { 
            public  String title; 
            public  String description; 
            public  String link; 
            public  String pubDate; 
            
            public String toString() 
            { 
                return (this.title + ": " + this.pubDate + "n" + this.description); 
            } 
        } 
        
    }

    Using RssParser.java :

    RssParser rp = new RssParser("<RSS Feed URL>"); 
    rp.parse(); 
    RssFeed feed = rp.getFeed();
    // Listing all categories & the no. of elements in each category 
    if (feed.category != null) 
    { 
     System.out.println("Category List: "); 
     for (String category : feed.category.keySet()) 
     { 
      System.out.println(category 
        + ": " 
        + ((ArrayList<Item>)feed.category.get(category)).size()); 
     } 
    }
    // Listing all items in the feed 
    for (int i = 0; i < feed.items.size(); i++) 
     System.out.println(feed.items.get(i).title); 
     
    • sciafranz 9:20 pm on September 9, 2008 Permalink

      thank you!! I need it!

    • Subinkrishna G 10:22 am on September 10, 2008 Permalink

      My pleasure 🙂

    • Subinkrishna G 12:55 pm on January 22, 2009 Permalink

      This is a very basic RSS parser. My intension was to write a parser for J2ME enabled mobile devices. Thats why I wrote it with SAX. By changing some of the Collection objects used in the code we can use it in J2ME (e.g. HashMap to Hashtable).

      But I personally prefer to use JDOM parser for all XML parsing needs. JDOM is again SAX based and gives us a DOM-like document object. And it’s very simple to use too. Find more about it here: http://www.jdom.org

      I will try to post a JDOM based parser soon.

    • vandershraaf 12:49 am on December 29, 2010 Permalink

      Dude, this is amazing. Thanks!

    • Isaac Ojeda 1:31 pm on January 22, 2011 Permalink

      Thanks!!! 😀

    • glennbech 4:53 am on March 28, 2011 Permalink

      Thanks. I need to to something like this in Android. I thought about using Rome, but it depends on JDOM, and before you know it 200kb + is added to the download just for the XML parsing.

      Great example on how to do stuff the “right way” on mobile!

    • Subinkrishna G 10:26 am on March 28, 2011 Permalink

      Sure. This code is written back in 2007 and may be missing some key. Please feel free to customize it for your needs.

  • Subinkrishna Gopi 3:32 pm on July 16, 2007 Permalink |  

    Issues need to be tackled while developing J2ME applications 

    While developing an application in J2ME, the programmers need to take care of lot of things (rather I would say limitations) and should tackle it down. Normal Java applications may enjoy the richness of memory, processor speed and things like that (may also get a lot of support from the native environment also).

    But J2ME doesn’t offer us such a fruit. I have listed some of the design areas where we need to focus while developing J2ME applications:

    Memory
    Instead of memory its better to say “lack of memory”. The J2ME is a lighter version of Java which is targeting devices with minimal amount of volatile & non-volatile memory. So the point is clear, right?

    But these days, even memory is not a constraint. B’ coz almost all devices comes with extendable memory. But still should be an area of concern.

    No Multi-Window Support
    There is no multi-window support in J2ME. So the application UI should be designed properly so that the user should be able to navigate it properly (without much effort to understand the UI).

    No File System Support
    J2ME does have file system support (JSR 75). But most of the devices still doesn’t support JSR 75. What the programmer can do is, use the RMS (Record Management System) feature.

    Device Dependency
    J2ME applications are too much device dependent. Then you may be thinking about the promise (“write once, run anywhere”) made by Sun, right? To some extend, yes it do keep its promise. But once you start running the same application in different devices, you will come to know how much effort the application developer need to do to make it working properly in all devices.

    So, what developers can do is to write the code in such a way to minimize the amount of porting needed. One way I can suggest is to have a clear separation of general purpose and device dependent code segments.

     
    • anushar83 3:19 pm on July 25, 2007 Permalink

      Hi,
      After reading this article Iam confused to some extend. First of all Iam unable to get the context of multi window. Moreover about the File system support, I believe J2ME has file connection APIs.I think JSR75 explians about this.J2ME supports File system along with the RMS record store.
      Regards,
      Me

    • Subin 4:00 pm on July 25, 2007 Permalink

      Wow! So you kept your promise.

      So here goes my thoughts:
      1. Multi-window concept is nothing but the use of multiple windows in an application just like what we do with Java Swing, SWT etc. What I was trying to say, there should be a proper UI design for a J2ME application to make it more usable to the user.

      2. Yup, J2ME has its file connection APIs. Now there is a PDAP (PDA Profile) which does it for us. But I am not sure about which all handsets support that. Its JSR 75. There is two sepecification requests in JSR 75. PIM & File Connection.

      And RMS is not a file system. RMS can be considered as a record management system which can be a much scaled down version of a DBMS.

      Thanks & Regards,
      Subin

  • Subinkrishna Gopi 3:15 pm on July 13, 2007 Permalink |
    Tags: collections, , map, ,   

    TreeMap vs HashMap 

    Both TreeMap & HashMap are two different implementation of the Map interface. Even though this post is titled “TreeMap vs HashMap” I would like to say how they are connected and how much similar they are.

    Both TreeMap & HashMap are not synchronized. To make it synchronized we have to explicitly call Collections.synchronizedMap( mapName ) . Both supports “fail-fast” iterators. Both of them doesn’t support duplicate keys.

    HashMap

    HashMap allows null as both keys and values. HashMap is useful when we need to access the map without cosidering how they are added to the map (means, unordered lookup of values using their keys). HashMap is synchronized while it is being looked up. HashMap doesn’t allow duplicated entries.

    The performance of HashMap is based on two optional parameter which we can specify during the creation of the HashMap. Initial capacity & load factor. Initial capacity is the bucket size assigned to a HashMap during it’s creation. Load factor decides when the HashMap needs to be expanded. If the load factor is 0.75, the size will be increased when the current size of the map crosses 75% of its capacity.

    TreeMap

    The basic difference between HashMap & TreeMap is that, in a TreeMap the elements are stored in a tree. TreeMap allows us to retrieve the elements in some sorted order defined by the user. So we can say that TreeMap is slower than HashMap. This is the only implementation based on SortedMap interface.

    TreeMap allows us to specify an optional Comparator object during its creation. The keys should be compatible with the comparator specified. This comparator decides the order by which the keys need to be sorted.

    public interface Comparator
    {
        public int compare (Object object1, Object object2);
        public boolean equals (Object object);
    }
    

    If we are not specifying the comparator, TreeMap will try to sort the keys in the natural order. Means will consider them as instances of Comparable interface.

    public interface Comparable
    {
        public int compareTo (Object objectToCompare);
    }
    

    Classes like Integer, String, Double etc implements Comparable interface. So if we are to use an object of a custom class as the key, ensure that it’ s class implements the Comparable interface.

    public class MyCustomKey implements Comparable
    {
        private int value;
        public MyCustomKey(int value)
        {
           this.value = value;
        }           
    
        public int compareTo (MyCustomKey key)
        {
           int comparison = 0;           
    
           // Note:
           // Return -1 if this.value < key.value
           // Return  0 if this.value = key.value
           // Return  1 if this.value > key.value           
    
           return (comparison);
        }
    }
    

    A common mistake that everyone does is not to override the hashcode(). If we are failing to do so, map.get(new MyCustomKey(<value>)); may not give you what you were expecting. So it is always adviced to override the hashCode() if objects of that class is being used as a key.

    public class MyCustomKey implements Comparable
    {
        private int value;
        public MyCustomKey(int value)
        {}
        public int compareTo (MyCustomKey key)
        {}        
    
        public int hashCode()
        {
            // Note:
            // If two objects are equal then their corresponding hashCode ()
            // should return the same value too.
            return (this.value * 199);
        }
    }
    
     
  • Subinkrishna Gopi 12:27 pm on July 12, 2007 Permalink |  

    Oracle Releases Database 11g 

    Oracle has introduced Oracle Database 11g, which claims to enable organisations take control of their enterprise information, gain better business insight, and adapt to an increasingly changing competitive environment.

    The new release extends Oracle’s database clustering, data centre automation, and workload management capabilities and claims to tackle transaction processing, data warehousing, and content management applications.

    Oracle Database 11g includes advanced self-management and automation to help organisations meet service level agreements. It features new data partitioning and compression capabilities, for cost-effective Information Lifecycle Management and storage management.

    For more details visit these links:
    http://www.oracle.com/database/index.html
    http://www.oracle.com

    Oracle Database 10g Downloads

    Source: tech2.com

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel