package com.rauser_ag.cocoon.transformation;

import java.io.IOException;

import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.avalon.framework.parameters.Parameters;

import org.apache.cocoon.ProcessingException;

import org.apache.cocoon.environment.SourceResolver;

import org.apache.cocoon.transformation.AbstractTransformer;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import org.xml.sax.helpers.DefaultHandler;

public class TestTransformer extends AbstractTransformer {
  
  public void setup(SourceResolver resolver_, Map objectModel_, String src_, 
                    Parameters params_)
   throws ProcessingException, SAXException, IOException {
  }

  public void startElement(String uri_, String loc_, String raw_, Attributes attrs_)
   throws SAXException {
    
    if (uri_.equals("http://rauser-ag.com/include")) {
      if ("include".equals(loc_)) {
        generate();
        return;
      }
    }

    super.startElement(uri_, loc_, raw_, attrs_);
  }
  
  public void endElement(String uri_, String loc_, String raw_)
   throws SAXException {
    
    if (uri_.equals("http://rauser-ag.com/include")) {
      if ("include".equals(loc_)) {
        return;        
      }
    }

    super.endElement(uri_, loc_, raw_);
  }  
  
  /**
   * Generate XML data.
   */
  public void generate() throws SAXException {
    try {
      String test = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?><test><text>Das ist ein Test</text></test>";
      
      SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setNamespaceAware(true);
      
      SAXParser parser = factory.newSAXParser();
      XMLReader reader = parser.getXMLReader();

      reader.setContentHandler(new DefaultHandler() {
        public void startElement(String uri_, String loc_, String raw_, Attributes attrs_) throws SAXException {
          contentHandler.startElement(uri_, loc_, raw_, attrs_);
        }
        
        public void endElement(String uri_, String loc_, String raw_) throws SAXException {
          contentHandler.endElement(uri_, loc_, raw_);
        }
        
        public void characters(char[] text_, int start_, int length_) throws SAXException {
          contentHandler.characters(text_, start_, length_);
        }
        
      });
      reader.parse(new InputSource(new java.io.StringReader(test))); //new InputSource(src_));
    } catch (Exception ex) {
      getLogger().error("", ex);
      throw new SAXException(ex);
    }
  }
}