
package icsTables;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.w3c.dom.*;
import java.io.*;
import java.util.Vector;

/**
 * This class contains the functions that help for xml file transformation
 * @author MC
 */
public class XMlXSLTClass {
    
	static final String JAXP_SCHEMA_LANGUAGE =
	    "http://java.sun.com/xml/jaxp/properties/schemaLanguage";

	static final String W3C_XML_SCHEMA =
	    "http://www.w3.org/2001/XMLSchema"; 
	
	static final String JAXP_SCHEMA_SOURCE =
	    "http://java.sun.com/xml/jaxp/properties/schemaSource";
	
    /** Creates a new instance of XSLTClass */
    public XMlXSLTClass() {
    }
    
    public Document document;
    
    /**
     * readXMLString
     * @param strXML
     * @return String
     */
    public String DomToString(Document doc)
    {
        String str = "";
        try
        {        
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer1 = tFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            StreamResult result2 = new StreamResult(stream);
            transformer1.transform(source, result2);
            str = stream.toString();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return str;
    }
    /**
     * DomToFile
     * @param doc
     * @param file
     */
    public void DomToFile(Document doc, File file)
    {
        try{
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer1 = tFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result2 = new StreamResult(file);
            transformer1.transform(source, result2);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    /**
     * readXMLString
     * @param strXML
     * @return
     */
    public Document readXMLString( String strXML )
    {
    	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try
		{
			DocumentBuilder builder = factory.newDocumentBuilder();
			document = builder.parse( strXML );
		}
		catch( SAXParseException spe)
		{
			System.out.println("\n** Parsing error" + ", line" + spe.getLineNumber());
			Exception x = spe;
			if( spe.getException() != null )
			{
				x = spe.getException();
			}
			x.printStackTrace();
		}
		catch( SAXException sxe )
		{
			Exception x = sxe;
			if( sxe.getException() != null )
				x = sxe.getException();
			x.printStackTrace();
		}
		catch( ParserConfigurationException pce )
		{
			pce.printStackTrace();
		}
		catch( IOException ioe )
		{
			ioe.printStackTrace();
		}
		return document;
    }
	
    /**
     * readXMLFile
     * @param fileName
     * @return Document
     */
	public Document readXMLFile( String fileName )
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try
		{
			File f = new File( fileName );
			DocumentBuilder builder = factory.newDocumentBuilder();
			document = builder.parse( f );
		}
		catch( SAXParseException spe)
		{
			System.out.println("\n** Parsing error" + ", line" + spe.getLineNumber());
			Exception x = spe;
			if( spe.getException() != null )
			{
				x = spe.getException();
			}
			x.printStackTrace();
		}
		catch( SAXException sxe )
		{
			Exception x = sxe;
			if( sxe.getException() != null )
				x = sxe.getException();
			x.printStackTrace();
		}
		catch( ParserConfigurationException pce )
		{
			pce.printStackTrace();
		}
		catch( IOException ioe )
		{
			ioe.printStackTrace();
		}
		return document;
	}
	
	/**
	 * printDocument
	 *
	 */
	public void printDocument()
	{
		try
		{
			TransformerFactory tFactory = TransformerFactory.newInstance();
			Transformer transformer = tFactory.newTransformer();
			DOMSource source = new DOMSource( document );
			StreamResult result = new StreamResult( System.out );
			transformer.transform( source, result );
		}
		catch( Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * printDocumentTransformed
	 * @param dataSrc
	 * @param styleSheet
	 * @param result
	 */
	public void printDocumentTransformed( String dataSrc, String styleSheet, StreamResult result )
	{
		try
		{
			TransformerFactory factory = TransformerFactory.newInstance();
			File fStyleSheet = new File( styleSheet );
		
			readXMLFile( dataSrc );
			StreamSource styleSource = new StreamSource( fStyleSheet );
			Transformer transformer = factory.newTransformer( styleSource );
			DOMSource source = new DOMSource( document );
			transformer.transform( source, result );
		}
		catch( Exception e)
		{
			e.printStackTrace();
		}
		
	}
	/**
	 * printDocumentDoubleTransformed
	 * @param dataSrc
	 * @param styleSheet1
	 * @param styleSheet2
	 * @param result
	 */
    public void printDocumentDoubleTransformed( String dataSrc, String styleSheet1, String styleSheet2, StreamResult result )
	{
		try
		{                                               
                        BufferedInputStream bis = new
                        BufferedInputStream(new FileInputStream(dataSrc));
                        InputSource input = new InputSource(bis);
                        SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
                        File fStyleSheet1 = new File( styleSheet1 );
                        File fStyleSheet2 = new File( styleSheet2 );
                        
                        StreamSource styleSource1 = new StreamSource( fStyleSheet1 );
                        StreamSource styleSource2 = new StreamSource( fStyleSheet2 );
                        XMLFilter filter1 = factory.newXMLFilter(styleSource1);
                        XMLFilter filter2 = factory.newXMLFilter(styleSource2);
		
			
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        spf.setNamespaceAware(true);
                        SAXParser parser = spf.newSAXParser();
                        XMLReader reader = parser.getXMLReader();
                        
                        filter1.setParent(reader);
                        filter2.setParent(filter1);
                        
                        // Set up the transformer to process the SAX events generated
                        // by the last filter in the chain
                        Transformer transformer = factory.newTransformer();
                        SAXSource transformSource = new SAXSource(filter2, input);
                        transformer.transform(transformSource, result);
			
			
		}
		catch( Exception e)
		{
			e.printStackTrace();
		}
		
	}
    /**
     * printDocumentDoubleTransformedFromDom
     * @param doc
     * @param styleSheet1
     * @param styleSheet2
     * @param result
     */   
    public void printDocumentDoubleTransformedFromDom( Document doc, String styleSheet1, String styleSheet2, StreamResult result )
	{
		try
		{
                    
						// Use a Transformer for output
                        TransformerFactory tFactory = TransformerFactory.newInstance();
                        Transformer transformer1 = tFactory.newTransformer();
                        DOMSource source = new DOMSource(doc);
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        StreamResult result2 = new StreamResult(stream);
                        transformer1.transform(source, result2);
                        
            
                        String str = stream.toString();
                        str = str.replaceFirst("<DIM xmlns=\"http://www.nist.X73.gov\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-Instance\" xsi:noNameSpaceLocation=\"c:/ICS/xml/ICS-Tool$$.xsd\">"
,"<DIM>");
                        //System.out.println(str);
                        InputSource input = new InputSource(new StringReader(str));
                        SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
                        File fStyleSheet1 = new File( styleSheet1 );
                        File fStyleSheet2 = new File( styleSheet2 );
                        
                        StreamSource styleSource1 = new StreamSource( fStyleSheet1 );
                        StreamSource styleSource2 = new StreamSource( fStyleSheet2 );
                        XMLFilter filter1 = factory.newXMLFilter(styleSource1);
                        XMLFilter filter2 = factory.newXMLFilter(styleSource2);
		
			
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        spf.setNamespaceAware(true);
                        SAXParser parser = spf.newSAXParser();
                        XMLReader reader = parser.getXMLReader();
                        
                        filter1.setParent(reader);
                        filter2.setParent(filter1);
                        
                        // Set up the transformer to process the SAX events generated
                        // by the last filter in the chain
                        Transformer transformer = factory.newTransformer();
                        SAXSource transformSource = new SAXSource(filter2, input);
                        transformer.transform(transformSource, result);
			
			
		}
		catch( Exception e)
		{
			e.printStackTrace();
		}
		
	}
	/**
	 * printDocumentTransformedFromXMLString
	 * @param XMLSrc
	 * @param styleSheet
	 * @param result
	 */
	public void printDocumentTransformedFromXMLString( String XMLSrc, String styleSheet, StreamResult result )
	{
		try
		{
			TransformerFactory factory = TransformerFactory.newInstance();
			File fStyleSheet = new File( styleSheet );
		
			readXMLString( XMLSrc );
			StreamSource styleSource = new StreamSource( fStyleSheet );
			Transformer transformer = factory.newTransformer( styleSource );
			DOMSource source = new DOMSource( document );
			transformer.transform( source, result );
		}
		catch( Exception e)
		{
			e.printStackTrace();
		}
		
	}
	
	/**
	 * printDocumentTransformedFromDoc
	 * @param doc
	 * @param styleSheet
	 * @param result
	 */
	public void printDocumentTransformedFromDoc( Document doc, String styleSheet, StreamResult result )
	{
		try
		{
			TransformerFactory factory = TransformerFactory.newInstance();
			File fStyleSheet = new File( styleSheet );
		
			StreamSource styleSource = new StreamSource( fStyleSheet );
			Transformer transformer = factory.newTransformer( styleSource );
			DOMSource source = new DOMSource( doc );
			transformer.transform( source, result );
		}
		catch( Exception e)
		{
			e.printStackTrace();
		}
		
	}
	
	/**
	 * saveDocumentTransformed
	 * @param dataSrc
	 * @param styleSheet
	 * @param fileName
	 */
	public void saveDocumentTransformed( String dataSrc, String styleSheet, String fileName )
	{
		printDocumentTransformed(dataSrc, styleSheet, new StreamResult( new File(fileName)));
	} 
    
	/**
	 * getStringDocumentTransformed
	 * @param dataSrc
	 * @param styleSheet
	 * @return
	 */
    public String getStringDocumentTransformed(String dataSrc, String styleSheet)
    {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        printDocumentTransformed(dataSrc, styleSheet, new StreamResult( stream ));  
        return stream.toString();
    }
    
    /**
     * getStringDocumentTransformedFromStringXML
     * @param dataSrc
     * @param styleSheet
     * @return
     */
    public String getStringDocumentTransformedFromStringXML(String dataSrc, String styleSheet)
    {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        printDocumentTransformedFromXMLString(dataSrc, styleSheet, new StreamResult( stream ));  
        return stream.toString();
    }
    
    /**
     * getStringDocumentTransformedFromDoc
     * @param doc
     * @param styleSheet
     * @return
     */
    public String getStringDocumentTransformedFromDoc(Document doc, String styleSheet)
    {
    	document = doc;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        printDocumentTransformedFromDoc(doc, styleSheet, new StreamResult( stream ));  
        return stream.toString();
    }
    /**
     * getStringDocumentDoubleTransformedFromDom
     * @param doc
     * @param styleSheet1
     * @param styleSheet2
     * @return
     */
    public String getStringDocumentDoubleTransformedFromDom( Document doc, String styleSheet1, String styleSheet2 )
    {
	    ByteArrayOutputStream stream = new ByteArrayOutputStream();
	    printDocumentDoubleTransformedFromDom(doc, styleSheet1, styleSheet2, new StreamResult( stream ));  
	    return stream.toString();
       
    }
    /**
     * isXmlFileValidate
     * @param xmlFileName
     * @param xmlSchema
     * @return
     */
    public Vector XmlFileValidate(File xmlFileName, String xmlSchema)
    {
    	
    	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    	factory.setNamespaceAware(true);
    	factory.setValidating(true);
    	Validator handler=new Validator();        
		
		factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
		factory.setAttribute(JAXP_SCHEMA_SOURCE,new File(xmlSchema)); 
		DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();		
			builder.setErrorHandler(handler); 
			builder.parse(xmlFileName);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}		
    	return handler.Error;
    }
    /**
     * Validator
     * @author maria
     *
     */
    public class Validator extends DefaultHandler 
    {
        public boolean validationError = false;  
        public SAXParseException saxParseException = null;
        public Vector<String> Error;
        public Validator()
        {
        	super();
        	Error = new Vector<String>();
        }
        public void error(SAXParseException exception) throws SAXException {
           validationError = true;
           saxParseException = exception;
           Error.add(exception.getMessage());
           System.out.println(exception);
        }     
        public void fatalError(SAXParseException exception) throws SAXException {
           validationError = true;	    
           saxParseException=exception;	
           Error.add(exception.getMessage());
           System.out.println(exception);     
        }		    
        public void warning(SAXParseException exception)throws SAXException {
           System.out.println(exception); 
        }	
     }
}
