/*
 *	The tauDOM API Sample, Version 1.0
 *
 *	Copyright (c) 1999-2002
 *	The Computer Science Department of University of Arizona.
 *	All rights reserved.
 *
 *	This sample program demonstrates how to use the tauDOM API to 
 *	access temporal XML document. It calculats the number of nodes
 *	in a temporal XML document in representational, current and 
 *	sequenced mode respectively. A sample temporal XML document can 
 *	be downloaded from the tauDOM homepage (http://www.cs.arizona.edu/tau/tdom/).
 * 
 *
 *  Instructions:
 *  1. Download Xerces Java version 2.2.1; place the jar in the current directory.
 *     Download tDom; place the jar in the current directory.
 *
 *  2. Compile the program with:
 *      javac Sample.java -cp ./xerces-2.2.1.jar:./tdom.jar
 *
 *	3. Run the program with:
 *		java Sample sample.xml 
 *
 */
import org.w3c.dom.*;
import org.w3c.dom.ls.*;

import org.apache.xerces.parsers.*;

import java.util.*;
import java.text.*;
import java.io.*;

/**
 *	Calculate the number of nodes in a temporal XML document.
 */
public class Sample
{
	static TDocumentImpl tdoc;

	public static void main(String[] args) throws Exception{
		/**
		 *	parse the temporal XML document
		 */
		DOMParser parser = new DOMParser();
		parser.parse(args[0]);

		Document txml_doc = parser.getDocument();

		/**
		 *	Instantiate TDocument from Document 
		 */
		tdoc = new TDocumentImpl(txml_doc);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		/**
		 *	Calculate the number of nodes in representational mode
		 */
		tdoc.setModeRepresentational();

		System.out.println("In representational mode, there are " + 
							count_children(tdoc.getDocumentElement()) + 
							" nodes.");

		tdoc = new TDocumentImpl(txml_doc);

		/**
		 *	Calculate the number of nodes in current mode
		 */
		tdoc.setModeCurrent("yyyy-MM-dd", "2002-01-15");

		System.out.println("In current mode, there are " + count_children(tdoc.getDocumentElement()) + 
							" nodes.");
		
		/**
		 *	Calculate the number of nodes in sequenced mode
		 */
		tdoc = new TDocumentImpl(txml_doc);
		tdoc.setModeSequenced("yyyy-MM-dd", "2002-02-15", "2002-05-04");

		System.out.println("In sequenced mode, there are " + count_children(tdoc.getDocumentElement()) + 
							" nodes.");
	}
	
	static int count_children(Element e){
		NodeList cl = e.getChildNodes();
		
		int node_num = cl.getLength();
		
		for (int i = 0; i < cl.getLength(); i++){
			if (cl.item(i) instanceof Element)
				node_num += count_children((Element)cl.item(i));
		}
		
		return node_num;
	}
}
