package jp.ossc.nimbus;

import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import org.testng.Assert;

import jp.ossc.nimbus.core.MetaData;

public class TestUtility{

    
    public static Element createElement(String xml) throws Exception{
        return createElement(xml, null);
    }
    
    public static Element createElement(String xml, String encoding) throws Exception{
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(
            new InputSource(
                new ByteArrayInputStream(encoding == null ? xml.getBytes() : xml.getBytes(encoding))
            )
        );
        return doc.getDocumentElement();
    }
    
    public static <T extends MetaData> T importXML(T metaData, String xml) throws Exception{
        return importXML(metaData, xml, null);
    }
    
    public static <T extends MetaData> T importXML(T metaData, String xml, String encoding) throws Exception{
        metaData.importXML(createElement(xml, encoding));
        return metaData;
    }
    
    public static void assertMetaDataEquals(MetaData result, MetaData expected){
        StringBuilder buf = new StringBuilder();
        String resultStr = null;
        String expectedStr = null;
        if(result != null){
            result.toXML(buf);
            resultStr = buf.toString();
        }
        buf.setLength(0);
        if(expected != null){
            expected.toXML(buf);
            expectedStr = buf.toString();
        }
        Assert.assertEquals(resultStr, expectedStr);
    }
}
