package org.injac.indexing.lius.XML;


import java.io.IOException;
import java.util.Collection;

import org.apache.lucene.document.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.StringReader;

import ca.ulaval.bibl.lius.Lucene.LuceneActions;
import ca.ulaval.bibl.lius.index.XML.XmlFileIndexer;


/**
 * Subclass taking file attribute as XML string instead of file path
 * @author François Jannin
 *
 */
public class XmlStreamIndexer extends XmlFileIndexer {

	public Document createLuceneDocument(String xml, Collection liusFields) {
	    LuceneActions la = new LuceneActions();
	   Object jdomDoc= parse(xml);
	   // use implementation of XmlFileIndexer.getPopulatedCollection testing type of file
       Collection coll = getPopulatedCollection(jdomDoc, liusFields);
	   Document doc = la.populateLuceneDoc(coll);
	   return doc;
	  }
	
	/**
	   * Permet de parser une chaine XML et de retourner un objet de type JDOM Document.
	   * <br/><br/>
	   * Parse an XML file and returns a JDOM object.
	   */
	  public Object parse(String xmlString) {
	    org.jdom.Document xmlDoc = new org.jdom.Document();
	    try {
	      SAXBuilder builder = new SAXBuilder();
	      builder.setValidation(false);
	      StringReader stringReader = new StringReader(xmlString);
	      xmlDoc = builder.build(stringReader);
	    }
	    catch (JDOMException e) {
	      e.printStackTrace();
	    }
	    catch (IOException e) {
	      e.printStackTrace();
	    }
	    return xmlDoc;
	  }

}
