package gov.epa.state.sample.axis.converter;


import gov.epa.cdx.axis.v10.vo.QueryResult;
import gov.epa.cdx.commons.exception.CDXException;
import gov.epa.cdx.commons.exception.CDXServerException;
import gov.epa.cdx.commons.exception.CDXErrorCode;

import org.apache.axis.message.MessageElement;
import org.apache.axis.message.*;

import org.w3c.dom.Element;
import gov.epa.cdx.commons.exception.*;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;

/**

 * User: David Dundua
 * Date: May 29, 2003
 * Time: 5:52:42 PM
 */
public class ResultConverter
{

/**
 * This method converts byte array into sqlResult object.
 * @param byteArray - incoming byte array
 * @return sqlResult - sqlResult representation of the incoming array
 * @throws gov.epa.cdx.commons.exception.CDXException
 * @deprecated QueryResult is no longer used
 */
	public static QueryResult ToQueryResult(byte[] byteArray) throws CDXException
	{
		QueryResult doc = new QueryResult();
        Element element = null;

        try
		{
			element = DocumentBuilderFactory
				.newInstance()
				.newDocumentBuilder()
				.parse(
				new ByteArrayInputStream(byteArray)).getDocumentElement();
		}
		catch (Exception e)
		{
			throw new CDXServerException (CDXErrorCode.INTERNAL_SERVER_ERROR, e);
		}

				MessageElement messageEl =
			new MessageElement(element);

		MessageElement[] messageElArray = new MessageElement[1];
		messageElArray[0] = messageEl;
		doc.set_any(messageElArray);
		return doc;
	}

    public static String validateWellformness(String xmlDocument) throws CDXException
    {
          Element element = null;

        try
		{
			element = DocumentBuilderFactory
				.newInstance()
				.newDocumentBuilder()
				.parse(
				new ByteArrayInputStream(xmlDocument.getBytes())).getDocumentElement();
		}
		catch (Exception e)
		{
			throw new CDXServerException (CDXErrorCode.INTERNAL_SERVER_ERROR, e);
		}
        //if we got here that means document is well-formed
		return xmlDocument;
    }
}