/*
Copyright (C) 2000-2010  Ministere de la culture et de la communication (France), AJLSM
See LICENCE file
 */
package fr.gouv.culture.sdx.sitemap.serialization;

/*
Based on cocoon code by Stephan and Carsten
*/
//from http://heml.mta.ca/heml-cocoon/
//package org.heml.cocoon.serialization;

import org.apache.avalon.framework.CascadingRuntimeException;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.cocoon.serialization.AbstractTextSerializer;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;

public class GzipXMLSerializer extends AbstractTextSerializer {

	private TransformerHandler handler;
	private GZIPOutputStream gzop;

	public GzipXMLSerializer() {
	}

	/**
	 * Set the configurations for this serializer.
	 */
	public void configure(Configuration conf)
			throws ConfigurationException {
		super.configure(conf);
		this.format.put(OutputKeys.METHOD, "xml");
	}

	public void setOutputStream(OutputStream out) {
		try {
			gzop = new GZIPOutputStream(out);
			super.setOutputStream(out);
			this.handler = getTransformerFactory().newTransformerHandler();
			handler.getTransformer().setOutputProperties(format);
			handler.setResult(new StreamResult(gzop));
			this.setContentHandler(handler);
			this.setLexicalHandler(handler);
		} catch (Exception e) {
			getLogger().error("XMLSerializer.setOutputStream()", e);
			throw new CascadingRuntimeException("XMLSerializer.setOutputStream()", e);
		}
	}

	public void endDocument() {
		try {
			super.endDocument();
			gzop.finish();
			gzop.close();
//		   super.endDocument(); handler needs to be informed of endDocument event before stream is managed

		} catch (Exception e) {
			System.out.println("endDocument() died: " + e);
		}
	}

	/**
	 * Recycle the serializer. GC instance variables
	 */
	public void recycle() {
		super.recycle();
		this.handler = null;
	}
}

