package dom;

import java.io.*;
import org.w3c.dom.*;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/*
 * This software is an adaptation of Writer.java that comes with Xerces. 
 * It can be used to validate xml files with either a DTD or schema.
 * Writer also displays the xml file and consists of voluntary contributions 
 * made by many individuals on behalf of the Apache Software Foundation 
 * and was originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.apache.org.
 */
public class DOMValidator 
{
	/** Validation feature id (http://xml.org/sax/features/validation). */
    protected static final String VALIDATION_FEATURE_ID 
    	= "http://xml.org/sax/features/validation";

    /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */
    protected static final String SCHEMA_VALIDATION_FEATURE_ID 
    	= "http://apache.org/xml/features/validation/schema";

    /** Default parser name. */
    protected static final String PARSER_NAME = "dom.wrappers.Xerces";

    /** Main */
    public static void main(String args[]) 
    {
		System.out.println ("DTD and Schema Parser and Validator");
        
        BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
        String xmlfile = null, option = null;
        try
        {	
        	System.out.print ("Option, v for DTD validation or s for schema validation: ");
        	option = stdin.readLine ();
        	System.out.print ("XML File Name: ");
        	xmlfile = stdin.readLine ();
    	} catch (IOException e) {System.out.println ("No xml file name or option");}
        
        boolean validation = false;
        boolean schemaValidation = false;
        
		if (option.equalsIgnoreCase("v")) validation = true;	
		if (option.equalsIgnoreCase("s")) schemaValidation = true;
		
		ParserWrapper parser = null;
		try // Create parser.
		{
			parser = (ParserWrapper)Class.forName(PARSER_NAME).newInstance();	
		}
		catch (Exception e) {System.out.println("Error: Unable to instantiate parser.");}

		try // Set parser features.
		{
			parser.setFeature(VALIDATION_FEATURE_ID, validation);
			parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
		} catch (SAXException e) {System.out.println ("SAXException");}
				
		try // Parse the document.
		{
			Document document = parser.parse (xmlfile);
			System.out.println ("Document parse is finished.");
		} catch (SAXParseException e) {/* ignore*/ }
		catch (Exception e) {System.err.println("error: Parse error occurred.");}

    } // main

}  // class DOMValidator

