FileDocCategorySizeDatePackage
ScheduleJDOM.javaAPI DocExample1604Sun Sep 02 14:59:02 BST 2001chap4

ScheduleJDOM.java

package chap4;

import java.text.SimpleDateFormat;
import org.jdom.*;
import org.jdom.output.*;

/**
 * Produces a JDOM Document for a tv schedule.
 */
public class ScheduleJDOM {
    private SimpleDateFormat dateFmt = new SimpleDateFormat("hh:mm a");

    /**
     * Simple main() method for printing the XML document to System.out,
     * useful for testing.
     */
    public static void main(String[] args) throws Exception {
        Document doc = new ScheduleJDOM().getTodaysShows();
        new XMLOutputter("  ", true, "UTF-8").output(doc, System.out);
    }

    /**
     * @return a new JDOM Document for all TV shows scheduled for today.
     */
    public Document getTodaysShows() {
        Schedule sched = Schedule.getInstance();
        Show[] shows = sched.getTodaysShows();

        Element rootElem = new Element("schedule");

        for (int i=0; i<shows.length; i++) {
            rootElem.addContent(createShowElement(shows[i]));
        }
        return new Document(rootElem);
    }

    /**
     * A helper method to convert a Show object into a JDOM Element.
     */
    public Element createShowElement(Show show) {
        Element e = new Element("show");
        e.addContent(new Element("channel").setText(
                Integer.toString(show.getChannel())));
        e.addContent(new Element("from").setText(
                this.dateFmt.format(show.getStartTime())));
        e.addContent(new Element("to").setText(
                this.dateFmt.format(show.getEndTime())));
        e.addContent(new Element("title").setText(show.getTitle()));
        return e;
    }
}