package de.kompf.javaxml;

import java.io.*;
import java.net.URL;
import java.util.*;

import javax.xml.stream.*;
import javax.xml.stream.events.XMLEvent;

/**
 * Read and parse an AtomFeed XML stream and print the titles of the entries.
 * This examples uses the Cursor API from StAX.
 * @author Kompf
 *
 */
public class AtomFeedStreamReader {

  /**
   * Read the titles.
   * @param url The URI of the atom feed.
   * @return The list of titles.
   * @throws IOException
   * @throws XMLStreamException
   * @throws FactoryConfigurationError
   */
  public List<String> readNewsTitles(URL url) throws IOException,
      XMLStreamException, FactoryConfigurationError {
    List<String> titleList = new LinkedList<String>();

    InputStream in = url.openStream();
    try {
      XMLStreamReader reader = XMLInputFactory.newInstance()
          .createXMLStreamReader(in);
      while (reader.hasNext()) {
        int event = reader.next();
        //debugElement(reader, event);
        if (event == XMLEvent.START_ELEMENT
            && "entry".equals(reader.getLocalName())) {
          titleList.add(readEntry(reader));
        }
      }
    } finally {
      in.close();
    }

    return titleList;
  }

  private String readEntry(XMLStreamReader reader) throws XMLStreamException {
    String title = "";
    while (reader.hasNext()) {
      int event = reader.next();
      //debugElement(reader, event);
      if (XMLEvent.START_ELEMENT == event
          && "title".equals(reader.getLocalName())) {
        title = reader.getElementText();
        break;
      }
    }
    return title;
  }

  private void printTitles(List<String> titleList, PrintStream out) {
    for (String name : titleList) {
      out.println(name);
    }
  }
  
  @SuppressWarnings("unused")
  private void debugElement(XMLStreamReader reader, int event) {
    if (event == XMLEvent.START_ELEMENT) {
      System.out.printf("element: uri=%s localName=%s qName=%s\n", reader.getNamespaceURI(), reader.getLocalName(), reader.getName().toString());
    }
  }
  
  /**
   * MAIN.
   * @param args ignored.
   * @throws Exception If an error occurs.
   */
  public static void main(String[] args) throws Exception {
    // Heise News
    URL url = new URL("http://www.heise.de/newsticker/heise-atom.xml");
    // Twitter public time line
    @SuppressWarnings("unused")
    URL url2 = new URL("http://api.twitter.com/1/statuses/public_timeline.atom");
    
    AtomFeedStreamReader atomFeedStreamReader = new AtomFeedStreamReader();
    List<String> titles = atomFeedStreamReader.readNewsTitles(url);
    atomFeedStreamReader.printTitles(titles, System.out);
  }


}

