package org.injac.oai.util;

import java.io.File;
import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.oclc.oai.server.verb.OAIInternalServerError;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.*;
import java.net.*;
import org.apache.log4j.Logger;




public class XMLStreamParser {
	/**
	 * Document to parse
	 */
	static Logger logger = Logger.getLogger("INJAC_OAI");

	private Document xmlDoc=null;
	public XMLStreamParser(){
		super();
	}
	public XMLStreamParser(String xmlURL){
		super();
		InputStream is =getStreamFromURL(xmlURL); 
		initContext(is);
		
	}
	public InputStream getStreamFromURL(String xmlURL){
		 URLConnection urlConnection;
		 InputStream httpStream = null;
		 try
		 {
		   
		   URL fileURL = new URL(xmlURL); 
		   urlConnection = fileURL.openConnection();     // open URL (HTTP query)
		   httpStream = urlConnection.getInputStream();  // Open data stream
		   
		 }
		 catch(java.net.MalformedURLException ex)
		 {
			 logger.error(ex.getMessage());
		 }
		 catch(java.io.IOException ex)
		 {
			 logger.error(ex.getMessage());
		 }
		 return httpStream;
		
	}
	public String getStringFromURL(String url){
		String result="";
		InputStream is = getStreamFromURL(url);
		int count =0;
		int avail = 0;
		try {
			while((avail = is.available()) >0 ) {
				byte[] buff = new byte[avail];
				count = is.read(buff);
				result += new String(buff,0,count);
			}
			is.close();
		}catch(Exception e){
			logger.error(e.getMessage());
		}
		return result;
	}
	private void initContext(InputStream xmlStream)
	{
		
        //   Create DocumentBuilderFactory  
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
        // Configure it to ignore comments
        factory.setIgnoringComments(true);
        // Create the builder and parse the file
        
        try{
        	//   Load the specified XML document
        	DocumentBuilder builder = factory.newDocumentBuilder();
       
        	xmlDoc = builder.parse(xmlStream);
        	
        }catch(Exception ex)
		{
        	logger.error(ex.getMessage());
		}
        
      
    
	
	}

	public Document getXmlDoc() {
		return xmlDoc;
	}

	
}
