import java.io.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class ProductsSearch extends DefaultHandler
{
	String key = null;
	String currentTagName = null;
	String productNumber = null;
	String productID = null;
	String name = null;
	int flag = 0;

	public static void main(String[] args) throws Exception
	{
		System.out.println("Start of Products...");
		ProductsSearch readerObj = new ProductsSearch();
		readerObj.read(args[0]);
	}

	public void read(String fileName) throws Exception
	{
		XMLReader reader =
		  XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
		reader.setContentHandler(this);
		reader.parse(fileName);
	}

	public void startDocument() throws SAXException
	{
		System.out.println("Start document");
		InputStreamReader istream = new InputStreamReader(System.in);
		BufferedReader bufRead = new BufferedReader(istream);
		System.out.print("Enter the Product Number:");
		try
		{
			key = bufRead.readLine();
		}
		catch (IOException e) { }
		if (key.length() == 0)
		{
			System.out.println("No Product Number is entered");
			System.exit(0);
		}
	}

	public void endDocument() throws SAXException
	{
		if (flag == 0)
			System.out.println("No matching entry found...");
		System.out.println("End document");
	}

	public void startElement(String uri, String name, String qName, Attributes atts)
	{
		currentTagName = qName;		
	}

	public void endElement(String uri, String name, String qName)
	{ }

	public void characters(char ch[], int start, int length)
	{
		String value = new String(ch, start, length);	
		if (productID == null && currentTagName.equals("ProductID"))
		{
			productID = value;
		}
		if (name == null && currentTagName.equals("Name"))
		{
			name = value;
		}
		if (currentTagName.equals("ProductNumber"))
		{
			if (key.equals(value))
			{
				System.out.println("*******");
				System.out.println("Product ID:" + productID);
				System.out.println("Product Name:" + name);
				System.out.println("Product Number:" + key);
				System.out.println("*******");
				flag = 1;
			}
		}
		if (currentTagName.equals("Product"))
		{
			productID = null;
			name = null;
			productNumber = null;
		}
	}
}
