/*
 * XMLValidate.java
 *
 */

//package xml;

import java.io.*;

import java.util.ArrayList;

import javax.xml.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;
import javax.xml.validation.*;

import org.xml.sax.*;
import org.w3c.dom.*;

/**
 *
 * @author Robert Eckstein
 * Modified by Leigh L. Klotz, Jr. Leigh@WA5ZNU.org
 */
public class XMLValidate {
    
  /** Creates a new instance of Main */
  public XMLValidate(String[] args) {
    Schema schema = null;
    try {
      schema = getSchema(args);
    } catch (SAXException e) {
      System.err.println("SAXException caught...");
      //e.printStackTrace();
      return;
    }

    ArrayList xmlFilenames = getFilenames(args);

    // create a Validator object, which can be used to validate
    // an instance document
    Validator validator = schema.newValidator();

    for (int i = 0; i < xmlFilenames.size(); i++) {
      String xmlFilename = (String)(xmlFilenames.get(i));
      System.out.println("Validating file " + xmlFilename);
      try {

	// parse an XML document into a DOM tree
	DocumentBuilder parser =
	  DocumentBuilderFactory.newInstance().newDocumentBuilder();
	Document document = parser.parse(new File(xmlFilename));

	// validate the DOM tree

	validator.validate(new DOMSource(document));

      } catch (ParserConfigurationException e) {
	System.err.println("ParserConfigurationException caught...");
	//e.printStackTrace();
      } catch (SAXException e) {
	System.err.println("SAXException caught...");
	//e.printStackTrace();
      } catch (IOException e) {
	System.err.println("IOException caught...");
	//e.printStackTrace();
      }
    
    }
  }

  Schema getSchema(String args[]) throws SAXException {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory =
      SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    Source temp[] = new Source[args.length];
    int i;
    for (i = 0; i < args.length; i++) {
      String fn = args[i];
      if (fn.equals("-")) break;
      temp[i] = new StreamSource(new File(fn));
    }
    Source sources[] = new Source[i];
    System.arraycopy(temp, 0, sources, 0, i);
    return factory.newSchema(sources);
  }

  ArrayList getFilenames(String args[]) {
    ArrayList filenames = new ArrayList();
    boolean start = false;
    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-")) {
	start = true;
	continue;
      } 
      if (start) {
	filenames.add(args[i]);
      }
    }
    return filenames;
  }
    
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    XMLValidate main = new XMLValidate(args);
  }
    
}

